std::basic_ios<CharT,Traits>::eof
来自 cppreference.cn
bool eof() const; |
||
如果关联的流已到达文件末尾,则返回 true。 具体而言,如果 rdstate() 中设置了 eofbit
,则返回 true。
有关设置 eofbit
的条件列表,请参阅 ios_base::iostate。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
如果已发生文件末尾,则为 true,否则为 false。
[编辑] 注解
此函数仅报告最新 I/O 操作设置的流状态;它不检查关联的数据源。 例如,如果最近的 I/O 是 get(),它返回文件的最后一个字节,则 eof()
返回 false。 下一个 get()
无法读取任何内容并设置 eofbit
。 只有那时 eof()
才会返回 true。
在典型用法中,输入流处理会在任何错误时停止。 然后可以使用 eof()
和 fail() 来区分不同的错误情况。
[编辑] 示例
运行此代码
#include <cstdlib> #include <fstream> #include <iostream> int main() { std::ifstream file("test.txt"); if (!file) // operator! is used here { std::cout << "File opening failed\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for (int n; file >> n;) std::cout << n << ' '; std::cout << '\n'; if (file.bad()) std::cout << "I/O error while reading\n"; else if (file.eof()) std::cout << "End of file reached successfully\n"; else if (file.fail()) std::cout << "Non-integer data encountered\n"; }
[编辑] 参见
下表显示了 basic_ios 访问器(good()、fail() 等)对于 ios_base::iostate 标志的所有可能组合的值
ios_base::iostate 标志 | basic_ios 访问器 | |||||||
eofbit
|
failbit
|
badbit
|
good() | fail() | bad() | eof() | operator bool | operator! |
false | false | false | true | false | false | false | true | false |
false | false | true | false | true | true | false | false | true |
false | true | false | false | true | false | false | false | true |
false | true | true | false | true | true | false | false | true |
true | false | false | false | false | false | true | true | false |
true | false | true | false | true | true | true | false | true |
true | true | false | false | true | false | true | false | true |
true | true | true | false | true | true | true | false | true |
检查文件末尾 (函数) |