Problem with EOF when determine stream end(确定流结束时出现EOF问题)
问题描述
当我尝试使用函数 feof(FILE *) 确定文件结尾时,我发现它没有按预期工作:即使流结束,也需要额外读取.例如feof(FILE*) 如果在读取 10 个字节后立即调用具有 10 个字节数据的文件,则不会告诉 true.我需要一个额外的读取操作,当然返回 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."
我的问题是为什么还需要一个 read 以及如何确定文件的结尾,或者如果我不想要 feof-style?
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() 或任何变体 - 就这么简单.您希望它以某种方式预测下一次读取将失败,但这不是它的作用 - 它告诉您上一次读取的结果是什么.读取文件的正确方法是(在伪代码中):
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++ iostream 都是如此.
In other words, you need to test the result of the read operation. This is true for both C streams and C++ iostreams.
这篇关于确定流结束时出现EOF问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:确定流结束时出现EOF问题
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
