如何打印文件的内容? C 文件流

新手上路,请多包涵

我正在使用 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++ 很陌生

原文由 Lucas Smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 641
1 个回答

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

 #include <iostream>
#include <fstream>

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

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

原文由 Sam Varshavchik 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题