fwrite()文件损坏C ++ [英] fwrite() File Corruption C++
问题描述
我是C ++的新手(从C#迁移过来),所以我不确定这到底是怎么回事.我想做的是从文件中读取图像并将其写入输出文件,但是每当我这样做时,文件的某些部分似乎已损坏.
I'm somewhat of a newbie to C++ (moving from C#) so I'm not exactly sure what's going on here. What I'm trying to do is read an image out of a file and write it to an output file, but whenever I do parts of the file appear to be corrupt.
我已经检查了内存中的数据并且它实际上匹配,所以我认为罪魁祸首一定是fwrite()发生的事情,尽管它总是可能只是我做错了什么.
I've checked the data in memory and it actually matches, so I believe the culprit has to be something going on with fwrite(), although it could always just be something I'm doing wrong.
以下是一些示例数据: http://pastebin.com/x0eZin6K
Here's some sample data: http://pastebin.com/x0eZin6K
还有我的代码:
// used to figure out if reading in one giant swoop has to do with corruption
int BlockSize = 0x200;
// Read the file data
unsigned char* data = new unsigned char[BlockSize];
// Create a new file
FILE* output = fopen(CStringA(outputFileName), "w+");
for (int i = 0; i < *fileSize; i += BlockSize)
{
if (*fileSize - i > BlockSize)
{
ZeroMemory(data, BlockSize);
fread(data, sizeof(unsigned char), BlockSize, file);
// Write out the data
fwrite(data, sizeof(unsigned char), BlockSize, output);
}
else
{
int tempSize = *fileSize - i;
ZeroMemory(data, tempSize);
fread(data, sizeof(unsigned char), tempSize, file);
// Write out the data
fwrite(data, sizeof(unsigned char), tempSize, output);
}
}
// Close the files, we're done with them
fclose(file);
fclose(output);
delete[] data;
delete fileSize;
推荐答案
您是否正在Windows上运行此代码?对于不需要文本翻译的文件,必须以二进制模式打开它们:
Are you running this code on Windows? For files that don't need text translation, you must open them in binary mode:
FILE* output = fopen(CStringA(outputFileName), "wb+");
这就是您的输出文件中发生的情况:
This is what happens in your output file:
07 07 07 09 09 08 0A 0C 14 0D 0C
07 07 07 09 09 08 0D 0A 0C 14 0D 0C
^^
C运行时库可以帮助您将\n
转换为\r\n
.
The C runtime library helpfully translated your \n
to \r\n
.
这篇关于fwrite()文件损坏C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!