C++ ifstream: 读取整个文件内容 - 完整代码示例

学习如何使用 C++ ifstream 一次性读取整个文件的内容。本文提供一个完整代码示例,并解释如何使用 std::stringstream 存储和转换文件内容。

#include <iostream>
#include <fstream>
#include <sstream>

int main() {
    std::ifstream file("example.txt");
    if (file.is_open()) {
        std::stringstream buffer;
        buffer << file.rdbuf();
        std::string content = buffer.str();
        std::cout << content << std::endl;
    } else {
        std::cout << "Unable to open file" << std::endl;
    }

    return 0;
}

在这个例子中,我们打开名为"example.txt"的文件,并将其内容存储在一个字符串中。首先,我们创建一个std::stringstream对象来存储文件内容。然后,我们使用file.rdbuf()将文件内容读入stringstream对象中。最后,我们使用buffer.str()将stringstream对象转换为字符串,并将其打印到控制台上。

请确保将文件名替换为您要读取的实际文件名。

C++ ifstream: 读取整个文件内容 - 完整代码示例

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

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