简体   繁体   English

C ++:fread()返回非零,但仅在缓冲区中插入零

[英]C++: fread() returns non-zero, but only inserts zeros in to buffer

I am using fread() in C++ to read very large binary files (100MB-2GB). 我在C ++中使用fread()来读取非常大的二进制文件(100MB-2GB)。 The binary files are originally written from C++ by outputting a series of "packets". 二进制文件最初是通过输出一系列“数据包”由C ++编写的。 The packets are made of a "header" struct (that contains a size field) being directly written to a file, and then binary content with size equal to the size written in to the header. 数据包由直接写入文件的“标头”结构(包含大小字段)组成,然后由二进制内容组成,其大小等于写入标头的大小。 When reading the files, the packets are looped over, the header is read in to a struct and the content is read in to a void pointer of the size provided in the header. 读取文件时,数据包被循环,将标头读入结构,并将内容读入标头中提供的大小的空指针。

This is a known working method already implemented in other tools (meaning I can validate the files I am trying to read). 这是在其他工具中已经实现的已知工作方法(意味着我可以验证要读取的文件)。 Assume all files we are working with are validated. 假设我们正在使用的所有文件都经过验证。 In at least one file, my implementation of reading a binary file is working correctly. 在至少一个文件中,我读取二进制文件的实现工作正常。

However, with another file fread() starts acting funky for no apparent reason. 但是,对于另一个文件,fread()似乎没有明显的原因开始表现出时髦。 After many successful reads, I cleanly read the header portion of a packet using: 在多次成功读取之后,我使用以下命令清晰地读取了数据包的标头部分:

if (sizeof(stHdr) != fread((void *)&stHdr, 1, sizeof(stHdr), fi))

By cleanly reads, I mean fread() returns "sizeof(stHdr)" as expected, and feof(fi) and ferror(fi) both return 0. However... stHdr is completely filled with all zeros; 通过干净地读取,我的意思是fread()返回预期的“ sizeof(stHdr)”,并且feof(fi)和ferror(fi)均返回0。但是... stHdr完全用零填充; the value of every field in stHdr contains 0x0. stHdr中每个字段的值都包含0x0。 I have validated the binary file to be correctly formed, and to have data at the point that I am reading. 我已验证二进制文件的格式正确,并且在读取时具有数据。

Has anyone seen this before or know what could be causing it? 有没有人看过这个或者知道是什么原因造成的?

Thanks! 谢谢!

The problem ended up being a classic case of PEBKAC... 问题最终成为PEBKAC的经典案例。

Apparently my binary file did become corrupted at some point and actually did have a bunch of 0s in it. 显然我的二进制文件确实在某个时刻损坏了,实际上里面确实有一堆0。 I had copied it directly out of a repository and the file was validated before being put in to the repo, so I assumed it was good. 我已经直接将其从存储库中复制出来,并且在将文件放入回购库之前已对其进行了验证,因此我认为它很好。 Apparently something bad happened to my local version of the file and was the source of my problems. 显然我的文件的本地版本发生了问题,这是我问题的根源。

If your files are over 2GB, you'll need to enable large file support. 如果文件超过2GB,则需要启用大文件支持。

The quick and easy way to do this is to compile with -D_FILE_OFFSET_BITS=64 . 快速简便的方法是使用-D_FILE_OFFSET_BITS=64进行编译。 For the more targeted ways, and more details, see http://www.suse.de/~aj/linux_lfs.html 有关更具针对性的方式和更多详细信息,请参见http://www.suse.de/~aj/linux_lfs.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM