使用 C++ 20 的标准库可以使用 std::filesystem 库来读取整个文件,具体方法如下:

#include <iostream>
#include <fstream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    fs::path filePath("file.txt");
    if (fs::exists(filePath) && fs::is_regular_file(filePath)) {
        std::ifstream file(filePath);
        if (file) {
            std::string fileContent((std::istreambuf_iterator<char>(file)),
                                    std::istreambuf_iterator<char>());
            std::cout << "File content: " << fileContent << std::endl;
        } else {
            std::cerr << "Failed to open file." << std::endl;
        }
    } else {
        std::cerr << "File does not exist or is not a regular file." << std::endl;
    }
    return 0;
}

在上面的代码中,先使用 std::filesystem 库的 exists 和 is_regular_file 函数来检查文件是否存在并且是一个常规文件。然后使用 std::ifstream 打开文件并将其作为 std::istreambuf_iterator 的构造函数参数,从而读取整个文件内容到 std::string 对象中。最后输出文件内容。

需要注意的是,这种方法适用于读取较小的文件,对于大型文件,应该使用逐块读取的方法,以避免内存溢出。

c++ 20 读取整个文件最简单的方法

原文地址: https://www.cveoy.top/t/topic/sF1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录