确定流结束时出现 EOF 问题
当我尝试使用函数 feof(FILE *)
确定文件结尾时,我发现它无法按我的预期工作:即使流确实结束,也需要额外的读取。例如,如果在读取 10 个字节后立即在包含 10 个字节数据的文件上调用,feof(FILE*)
将不会返回 true。我需要一个额外的读取操作,当然会返回 0。然后 feof(FILE *)
会说“好吧,现在你到达了终点”。
为什么还需要一次 read
以及如何确定文件结尾,或者如果我不需要 feof
,如何知道文件流中还剩下多少字节-风格?
When I try to determine end of file with function feof(FILE *)
, I find it does not work as I expected: an extra read is required even if the stream does end. E.g., feof(FILE*)
will not return true if invoked on a file with 10 bytes data just after reading 10 bytes out. I need an extra read operation which of course returns 0. Then feof(FILE *)
will say "OK, now you reach the end."
Why is one more read
required and how can I determine end of file or how can I know how many bytes are left in a file stream if I don't want the feof
-style?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用 feof() 或任何变体——就这么简单。您希望它以某种方式预测下一次读取将失败,但这不是它的作用 - 它告诉您上一次读取的结果是什么。读取文件的正确方法是(伪代码):
换句话说,您需要测试读取操作的结果。对于 C 流和 C++ iostream 都是如此。
Do not use feof() or any variants—it is as simple as that. You want it to somehow predict the next read will fail, but that's not what it does - it tells you what the result of the previous read was. The correct way to read a file is (in pseudocode):
In other words, you need to test the result of the read operation. This is true for both C streams and C++ iostreams.