首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >fwrite()文件损坏C++

fwrite()文件损坏C++
EN

Stack Overflow用户
提问于 2011-08-08 09:26:19
回答 2查看 2.4K关注 0票数 5

我对C++ (从C#迁移)还是个新手,所以我不太清楚这里到底发生了什么。我尝试做的是从文件中读取图像并将其写入输出文件,但无论何时,文件的某些部分似乎已损坏。

我检查了内存中的数据,它实际上是匹配的,所以我相信罪魁祸首一定是fwrite()出了什么问题,尽管它总是可能是我做错了什么。

下面是一些示例数据:http://pastebin.com/x0eZin6K

我的代码是:

代码语言:javascript
复制
// 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;
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-08-08 09:28:55

你在Windows上运行这段代码吗?对于不需要文本翻译的文件,必须以二进制模式打开:

代码语言:javascript
复制
FILE* output = fopen(CStringA(outputFileName), "wb+");

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

代码语言:javascript
复制
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

票数 10
EN

Stack Overflow用户

发布于 2011-08-08 09:30:15

您需要将文件作为二进制文件打开,方法是在模式中添加"b“。

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6976992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档