gpt4 book ai didi

c++ - fwrite() 文件损坏 C++

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:56:49 24 4
gpt4 key购买 nike

我是 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;

最佳答案

您是否在 Windows 上运行此代码?对于不需要文本翻译的文件,必须以二进制方式打开:

FILE* output = fopen(CStringA(outputFileName), "wb+");

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

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

关于c++ - fwrite() 文件损坏 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6976992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com