Search code examples
c++filecorruptionfwrite

fwrite() File Corruption 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.

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;

Solution

  • 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.