fwrite() File Corruption C++

元气小坏坏 提交于 2019-12-10 15:11:12

问题


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.

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.

Here's some sample data: http://pastebin.com/x0eZin6K

And my code:

// 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;

回答1:


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
                  ^^

The C runtime library helpfully translated your \n to \r\n.




回答2:


You need to open the file as a binary by adding "b" to the mode.

http://www.cplusplus.com/reference/clibrary/cstdio/fopen/



来源:https://stackoverflow.com/questions/6976992/fwrite-file-corruption-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!