问题EOF时确定流结束 [英] Problem with EOF when determine stream end

查看:171
本文介绍了问题EOF时确定流结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试确定与功能的文件结束的feof(FILE *),我发现我所料不工作:是,即使需要额外读流不结束。例如的feof(FILE *)如果只是读10字节后出与10个字节的数据文件调用不会告诉如此。我需要一个额外的读操作,其中当然返回0,则的feof(FILE *)会说:好了,现在你到了最后。

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 tell 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 return 0, then feof(FILE *) will say "OK, now you reach the end."

我的问题是,为什么多了一个要求以及如何确定文件或如何知道到底在一个文件流离开,如果我不希望多少字节在的feof 风格?

My question is why does one more read required and how to determine end of file or how to know how many bytes left in a file stream if I don't want the feof-style?

感谢和问候。

推荐答案

不要使用的feof()或任何变种 - 它是如此简单。你想让它以某种方式predict下一个读会失败,但这不是它做什么 - 它告诉你什么是preVIOUS阅读的结果。读取文件的正确方法是(以伪code):

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):

while( read( file, buffer ) ) {
   do something with buffer
}

在换句话说,需要测试读出操作的结果。这是用于C流和C ++输入输出流真。

In other words, you need to test the result of the read operation. This is true for both C streams and C++ iostreams.

这篇关于问题EOF时确定流结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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