我一直在研究一个小程序,它将我需要的所有图像放到一个单独的文件中,但由于不知情的原因,当我尝试使用fstream写入文件时,它不会返回任何错误,但仍不会写入任何内容。fstream不写文件
为为例,我有一个简单的函数初始化一个新的文件:
void initPAK(fstream& pakfile, image firstImg)
{
PAKheader head;
head.sign[0] = 'P';
head.sign[1] = 'A';
head.sign[2] = 'K';
head.nbdata = 1;
head.index.push_back(sizeof(head.sign)+sizeof(head.nbdata)+sizeof(uint32_t));
if(pakfile.is_open())
{
pakfile.write(head.sign, sizeof(head.sign));
pakfile.write((char*)&head.nbdata, sizeof(head.nbdata));
for(uint32_t n=0; n<head.index.size(); n++)
{
pakfile.write((char*)&head.index[n], sizeof(head.index[n]));
}
pakfile.write((char*)&firstImg.width, sizeof(firstImg.width));
pakfile.write((char*)&firstImg.height, sizeof(firstImg.height));
pakfile.write((char*)&firstImg.channels, sizeof(firstImg.channels));
for(uint32_t n=0; n<firstImg.data.size(); n++)
{
pakfile.write((char*)&firstImg.data[n], sizeof(firstImg.data[n]));
}
}
else
{
cerr << "unable to open" << endl;
}
}
我用它这样的:
fstream fileop;
fileop.open("bin_file", fstream::in | fstream::out | fstream::trunc | fstream::binary);
unsigned char zdata[] = {
255, 0, 0,
0, 255, 0,
0, 0, 255,
};
image zimg;
zimg.width = 3;
zimg.height = 1;
zimg.channels = 3;
for(int i=0; i < 9; i++)
{
zimg.data.push_back(zdata[i]);
}
initPAK(fileop, zimg);
fileop.close();
但文件“bin_file”他从来不写,也不产生。我在另一个stackoverflow的问题中看到我应该使用flush(),但我也没有工作。他认为这个函数用来工作的最奇怪的东西,直到我相信我将fstream替换成fstream。 我在做什么错?
有些东西在你的代码中很棘手。 'initPAK'不会对'pakfile'做任何事情。 –
你有两个不同的文件'fileop'和'file'。你可能应该只使用其中之一。 –
您打开同一个文件两次,首先进行读取和写入,然后由于文件被锁定,您的第二次打开可能会失败。 –