温馨提示×

怎么使用C++标准库函数判断文件结尾

c++
小亿
84
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