为什么FREAD月初到达EOF? [英] Why is fread reaching the EOF early?

查看:481
本文介绍了为什么FREAD月初到达EOF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个C库读取文件到内存中。它跳过前54个字节的文件(头),然后读取其余的数据。我用fseek的确定文件的长度,然后用的fread文件中读取

I am writing a C library that reads a file into memory. It skips the first 54 bytes of the file (header) and then reads the remainder as data. I use fseek to determine the length of the file, and then use fread to read in the file.

循环运行一次,然后结束,因为达到EOF(没有错误)。在结束时,读取动作= 10624,FTELL(流)= 28726,和缓冲液含有28726的值。我希望FREAD读30,000字节,文件位置是30054当达到EOF。

The loop runs once and then ends because the EOF is reached (no errors). At the end, bytesRead = 10624, ftell(stream) = 28726, and the buffer contains 28726 values. I expect fread to read 30,000 bytes and the file position to be 30054 when EOF is reached.

C不是我的母语,所以我怀疑我有一个愚蠢的错误初学者的地方。

C is not my native language so I suspect I've got a dumb beginner mistake somewhere.

code是如下:

const size_t headerLen = 54;

FILE * stream;
errno_t ferrno = fopen_s( &stream, filename.c_str(), "r" );
if(ferrno!=0) {
  return -1;
}

fseek( stream, 0L, SEEK_END );
size_t bytesTotal = (size_t)(ftell( stream )) - headerLen; //number of data bytes to read
size_t bytesRead = 0;
BYTE* localBuffer = new BYTE[bytesTotal];
fseek(stream,headerLen,SEEK_SET);
while(!feof(stream) && !ferror(stream)) {
    size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-bytesRead,stream);
    bytesRead+=result;
}



根据您使用的参考,这是相当明显的是增加了B的模式标志就是答案。寻求的笨蛋徽章提名。 : - )

Depending on the reference you use, it's quite apparent that adding a "b" to the mode flag is the answer. Seeking nominations for the bonehead-badge. :-)

此引用在第二段第二句谈论它(虽然不是在自己的表)。

This reference talks about it in the second paragraph, second sentence (though not in their table).

MSDN 不讨论二进制标志,直到中途下来页。

MSDN doesn't discuss the binary flag until halfway down the page.

OpenGroup的提到了B标记是否存在等,但指出它应没有任何效果。

OpenGroup mentions the existance of the "b" tag, but states that it "shall have no effect".

推荐答案

也许这是一个二进制模式的问题。试着用R + B作为模式。

perhaps it's a binary mode issue. Try opening the file with "r+b" as the mode.

修改:作为评论指出RB很可能因为更好地匹配您的原意 R + b将打开它的读/写和RB是只读的。

EDIT: as noted in a comment "rb" is likely a better match to your original intent since "r+b" will open it for read/write and "rb" is read-only.

这篇关于为什么FREAD月初到达EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆