Visual Studio 中 EOF 在 EOF 之前
我在一个程序(在 Visual Studio 2005 中)中有这个片段:
if(_eof(fp->_file))
{
break;
}
当达到 eof 时,它打破了封闭循环。但该程序无法解析文件中的最后几千个字符。因此,为了找出发生了什么,我这样做了:
if(_eof(fp->_file))
{
cout<<ftell(fp)<<endl;
break;
}
现在我从 ftell 得到的答案与实际文件大小不同(并且更小)(这不是预期的)。我认为 Windows 可能对文件有一些问题,然后我这样做了:
if(_eof(fp->_file))
{
cout<<ftell(fp)<<endl;
fseek(fp, 0 , SEEK_END);
cout<<ftell(fp)<<endl;
break;
}
嗯,fseek() 给出了正确的答案(等于文件大小),并且初始 ftell() 失败了(如前所述)。
知道这里可能出什么问题吗?
编辑: 文件以“rb”模式打开。
I had this snippet in a program (in Visual Studio 2005):
if(_eof(fp->_file))
{
break;
}
It broke the enclosing loop when eof was reached. But the program was not able to parse the last few thousand chars in file. So, in order to find out what was happening, I did this:
if(_eof(fp->_file))
{
cout<<ftell(fp)<<endl;
break;
}
Now the answer that I got from ftell was different (and smaller) than the actual file-size (which isn't expected). I thought that Windows might have some problem with the file, then I did this:
if(_eof(fp->_file))
{
cout<<ftell(fp)<<endl;
fseek(fp, 0 , SEEK_END);
cout<<ftell(fp)<<endl;
break;
}
Well, the fseek() gave the right answer (equal to the file-size) and the initial ftell() failed (as previously told).
Any idea about what could be wrong here?
EDIT: The file is open in "rb" mode.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法在从
FILE*
获取的文件描述符上可靠地使用_eof()
,因为FILE*
流已被缓冲。这意味着fp
已经吸干了fp->_file
并将剩余字节存储在其内部缓冲区中。最终fp->_file
位于 eof 位置,而fp
仍然有字节可供读取。在读取操作之后使用feof()
来确定是否位于文件末尾,如果混合操作FILE* 以及对整数文件描述符进行操作的代码。
You can't reliably use
_eof()
on a file descriptor obtained from aFILE*
, becauseFILE*
streams are buffered. It means thatfp
has suckedfp->_file
dry and stores the remaining byte in its internal buffer. Eventuallyfp->_file
is at eof position, whilefp
still has bytes for you to read. Usefeof()
after a read operation to determine if you are at the end of a file and be careful if you mix functions which operate onFILE*
with those operating on integer file descriptors.如果您的文件 I/O 操作位于包装描述符的 FILE 流上,则不应直接在描述符上使用 _eof()。在应用程序从 FILE 流中读取所有数据之前,会发生缓冲,并且底层描述符将到达文件末尾。
在这种情况下,ftell(fp) 正在报告流的状态,您应该使用 feof(fp) 将它们保持在同一 I/O 域中。
You should not be using _eof() directly on the descriptor if your file I/O operations are on the FILE stream that wraps it. There is buffering that takes place and the underlying descriptor will hit end-of-file before your application has read all the data from the FILE stream.
In this case, ftell(fp) is reporting the state of the stream and you should be using feof(fp) to keep them in the same I/O domain.