命名空间
变体
操作

std::basic_ios<CharT,Traits>::eof

来自 cppreference.cn
< cpp‎ | io‎ | basic_ios
 
 
 
 
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";
}

[编辑] 另请参阅

下表显示了 ios_base::iostate 标志所有可能组合的 basic_ios 访问器(good()fail() 等)的值

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
检查文件结束
(函数) [编辑]