fwrite() 文件损坏 C++
我是 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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在 Windows 上运行此代码吗?对于不需要文本翻译的文件,您必须以二进制模式打开它们:
这就是输出文件中发生的情况:
C 运行时库有助于将您的
\n
翻译为\r\ n
。Are you running this code on Windows? For files that don't need text translation, you must open them in binary mode:
This is what happens in your output file:
The C runtime library helpfully translated your
\n
to\r\n
.您需要通过在模式中添加“b”来将文件作为二进制文件打开。
http://www.cplusplus.com/reference/clibrary/cstdio/fopen/
You need to open the file as a binary by adding "b" to the mode.
http://www.cplusplus.com/reference/clibrary/cstdio/fopen/