溫馨提示×

怎么使用C++標準庫函數判斷文件結尾

c++
小億
173
2024-04-18 10:53:08
欄目: 編程語言

在C++中,可以使用標準庫函數來判斷文件結尾。以下是一個示例代碼:

#include <iostream>
#include <fstream>
#include <string>

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

    if (!file.is_open()) {
        std::cerr << "Could not open file." << std::endl;
        return 1;
    }

    file.seekg(0, std::ios::end);
    std::streampos end = file.tellg();

    if (end == 0) {
        std::cout << "File is empty." << std::endl;
    } else {
        file.seekg(-1, std::ios::end);
        char c;
        file.get(c);

        if (c == '\n') {
            std::cout << "File ends with a newline character." << std::endl;
        } else {
            std::cout << "File does not end with a newline character." << std::endl;
        }
    }

    file.close();

    return 0;
}

在這個示例中,我們首先打開一個文件并獲取文件的大小。然后我們移動文件指針到文件末尾,并讀取最后一個字符。最后我們判斷文件是否以換行符結尾。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女