溫馨提示×

ifstream怎樣判斷文件結束

小樊
136
2024-06-26 14:30:52
欄目: 編程語言

在C++中,可以使用ifstream類的eof()函數來判斷文件是否已經結束。eof()函數會在到達文件末尾時返回true,否則返回false??梢栽谧x取文件時使用eof()函數來判斷是否已經讀取完整個文件。示例如下:

#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("example.txt");

    if (!file.is_open()) {
        std::cout << "Error opening file" << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(file, line)) {
        // Process the line
        std::cout << line << std::endl;

        // Check if end of file is reached
        if (file.eof()) {
            std::cout << "End of file reached" << std::endl;
            break;
        }
    }

    file.close();

    return 0;
}

在上面的示例中,我們首先打開一個文件example.txt,然后使用std::getline()函數逐行讀取文件內容。在每次讀取新的一行后,我們檢查是否已經到達文件末尾,如果是則輸出提示信息并跳出循環(huán)。

0