fwrite()文件损坏C++

Lan*_*der 5 c++ file fwrite corruption

我有点像C++的新手(从C#转移)所以我不确定这里发生了什么.我想要做的是从文件中读取一个图像并将其写入输出文件,但每当我执行该文件的某些部分时似乎已损坏.

我已经检查了内存中的数据并且它实际匹配,所以我认为罪魁祸首必须是fwrite(),尽管它总是只是我做错了.

以下是一些示例数据: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;
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 10

你在Windows上运行此代码吗?对于不需要文本转换的文件,必须以二进制模式打开它们:

FILE* output = fopen(CStringA(outputFileName), "wb+");
Run Code Online (Sandbox Code Playgroud)

这是输出文件中发生的情况:

07 07 07 09 09 08 0A 0C 14 0D 0C

07 07 07 09 09 08 0D 0A 0C 14 0D 0C
                  ^^
Run Code Online (Sandbox Code Playgroud)

C运行时库有助于将您转换\n\r\n.


jve*_*zey 5

您需要通过向模式添加"b"将文件作为二进制文件打开.

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