c++ - 如何打印出文件的内容? C++ 文件流

标签 c++ iostream fstream

我正在使用 fstream 和 C++,我想让我的程序做的就是将我的 .txt 文件的内容打印到终端。这可能很简单,但我在网上看了很多东西,但找不到任何对我有帮助的东西。我怎样才能做到这一点?这是我到目前为止的代码:

    #include <iostream>
#include <fstream>
using namespace std;

int main() {
    string output;
    ifstream myfile;
    ofstream myfile2;

    string STRING;
    myfile.open ("/Volumes/LFARLEIGH/Lucas.txt");

    myfile2 << "Lucas, It Worked";

        myfile >> STRING;
        cout << STRING << endl;
    myfile.close();


    return 0;
}

提前致谢。如果这很简单,请原谅我,因为我对 C++ 很陌生

最佳答案

当此功能已在标准 C++ 库中实现时,没有理由在这里重新发明轮子。

#include <iostream>
#include <fstream>

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

    if (f.is_open())
        std::cout << f.rdbuf();
}

关于c++ - 如何打印出文件的内容? C++ 文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35201919/

相关文章:

c++ - 容器的 Qt 内存管理

c++ - iostream,一些问题

c# - 是否可以在 Stream 参数中限制/要求某些功能?

c++ - 字符串流格式语法

c++ - fstream 不创建新文件

c++ - 如何为所有派生类型部分特化类模板?

c++ - 多态异常处理和编译器警告

c++ - 增量运算符不适用于 sizeof

c++ - ofstream中可以设置 "eof"吗?

c++ - 如何在 C++ 中同时读写 `fstream` 的文件?