名稱空間
變體
操作

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

來自 cppreference.com
< 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
檢查檔案結束
(函式) [編輯]