C++ 使用fstream读取/写入未签名字符*

C++ 使用fstream读取/写入未签名字符*,c++,fstream,unsigned-char,C++,Fstream,Unsigned Char,我对这个函数有问题。它给出的结果与原始数据不匹配。我找不到问题的原因。png的编码和解码工作正常,但当我在编码之间保存和加载像素原始数据时,它无法读取 #include <stdio.h> #include <tchar.h> #include "lodepng.h" void ProcessImage(const char* scrPath, const char* tmpPath, const char* dstPath) { unsigned error;

我对这个函数有问题。它给出的结果与原始数据不匹配。我找不到问题的原因。png的编码和解码工作正常,但当我在编码之间保存和加载像素原始数据时,它无法读取

#include <stdio.h>
#include <tchar.h>
#include "lodepng.h"
void ProcessImage(const char* scrPath, const char* tmpPath, const char* dstPath)
{
    unsigned error;
    unsigned char* pixelRaw;
    unsigned width, height;

    //load png
    error = lodepng_decode32_file(&pixelRaw, &width, &height, scrPath);
    if(error) 
        printf("error %u: %s\n", error, lodepng_error_text(error));

    //save pixels raw to file
    ofstream* _stream = new ofstream(tmpPath, ios::out|ios::binary);
    _stream->write(reinterpret_cast<const char*>(&pixelRaw), width * height);
    _stream->close();
    delete _stream;

    char* pixelRawTmp;
    unsigned char* pixelRaw2;

    // load pixels raws from file
    ifstream* _stream2 = new ifstream(tmpPath, ios::in|ios::binary);
    _stream2->read(pixelRawTmp,width*height);
    pixelRaw2 = reinterpret_cast<unsigned char*>(pixelRawTmp);
    delete _stream2;

    // saving png
    error = lodepng_encode32_file(dstPath, pixelRaw2, width, height);
    if(error) 
        printf("error %u: %s\n", error, lodepng_error_text(error));

    free(pixelRaw);
    free(pixelRawTmp);
    free(pixelRaw2);
}
#包括
#包括
#包括“lodepng.h”
void ProcessImage(常量字符*scrPath,常量字符*tmpPath,常量字符*dstPath)
{
无符号错误;
无符号字符*pixelRaw;
无符号宽度、高度;
//加载png
错误=lodepng_decode32_文件(&pixelRaw,&width,&height,scrPath);
如果(错误)
printf(“错误%u:%s\n”,错误,lodepng\u错误\u文本(错误));
//将原始像素保存到文件
ofstream*_stream=新的ofstream(tmpPath,ios::out | ios::binary);
_流->写入(重新解释投影(&pixelRaw),宽度*高度);
_流->关闭();
删除流;
char*pixelRawTmp;
无符号字符*pixelRaw2;
//从文件中加载像素
ifstream*_stream2=新的ifstream(tmpPath,ios::in | ios::binary);
_stream2->read(像素rawtmp,宽度*高度);
pixelRaw2=重新解释投影(pixelRawTmp);
删除(2);;
//保存png
错误=lodepng_encode32_文件(dstPath,pixelRaw2,宽度,高度);
如果(错误)
printf(“错误%u:%s\n”,错误,lodepng\u错误\u文本(错误));
免费(像素原始);
免费(pixelRawTmp);
自由(像素2);
}

为什么要将流的
分配给
/
ifstream
new
?在C++中,对于短命的对象,你不这样做。这种对象可以在堆栈上分配;是Java、C#和其他语言迫使您使用
new
分配对象。在C++中,你应该只做<代码> IFStultStudi2(TMPPATH,IOS:In iO::二进制);<代码>这与您的问题无关,但肯定是您应该更改的。谢谢您的建议。你猜得很好,我主要用C语言编程。我将从中更改,我希望读取的数据的大小是RGBA像素大小的
width
height
倍(大概是函数名的32位)。您也将
read()
插入
pixelRawTmp
,而不为其分配任何内存。我怀疑您需要使用
\u stream->write(pixelRaw,width*height);
而不是
\u stream->write(reinterpret\u cast(&pixelRaw),width*height);