简体   繁体   English

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

[英]How do I print out the contents of a file? C++ File Stream

I am using fstream and C++ and all I want my program to do is to print out to the terminal the contents of my .txt file.我正在使用 fstream 和 C++,我希望我的程序做的就是将我的 .txt 文件的内容打印到终端。 It may be simple, but I have looked at many things on the web and I can't find anything that will help me.这可能很简单,但我在网上看了很多东西,找不到任何对我有帮助的东西。 How can I do this?我怎样才能做到这一点? Here is the code I have so far:这是我到目前为止的代码:

    #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;
}

Thank you in advance.先感谢您。 Please forgive me if this is very simple as I quite new to C++如果这很简单,请原谅我,因为我对 C++ 很陌生

There's no reason to reinvent the wheel here, when this functionality is already implemented in the standard C++ library.当此功能已在标准 C++ 库中实现时,没有理由在这里重新发明轮子。

#include <iostream>
#include <fstream>

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

    if (f.is_open())
        std::cout << f.rdbuf();
}
#include <iostream>
#include <fstream>

int main()
{
    string name ;
    std::ifstream dataFile("file.txt");
    while (!dataFile.fail() && !dataFile.eof() )
    {
          dataFile >> name ;
          cout << name << endl;
    }

Try this, just modified at some places.试试这个,只是修改了一些地方。 You had tried to open a file using extracter (ie, ifstream) but overwriting this file using inserter (ie, ofstream) without opening the file, that ifstream and ofstream were two different classes.您曾尝试使用提取器(即,ifstream)打开文件,但使用插入器(即,ofstream)覆盖该文件而不打开文件,即ifstreamofstream是两个不同的类。 so, they don't understand.所以,他们不明白。

#include<iostream>
#include<fstream>

using namespace std;

int main(){

    string output;
    ifstream myfile;
    ofstream myfile2;

    string STRING;
    // output stream || inserting
    myfile2.open ("/Volumes/LFARLEIGH/Lucas.txt");

    myfile2 << "Lucas, It Worked";


    myfile2.close();

    // input stream || extracting

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

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


   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM