开发者

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;
        ZeroM开发者_JAVA技巧emory(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;


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.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜