Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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++

like image 658
Lucas Farleigh Avatar asked Feb 04 '16 13:02

Lucas Farleigh


People also ask

How do you display the contents of a file in C++?

File Handling in C++Create a stream object. Connect it to a file on disk. Read the file's contents into our stream object. Close the file.

What is an output file stream?

A file output stream is an output stream for writing data to a File or to a FileDescriptor .


2 Answers

There's no reason to reinvent the wheel here, when this functionality is already implemented in the standard C++ library.

#include <iostream>
#include <fstream>

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

    if (f.is_open())
        std::cout << f.rdbuf();
}
like image 90
Sam Varshavchik Avatar answered Oct 12 '22 02:10

Sam Varshavchik


#include <iostream>
#include <fstream>

int main()
{
    string name ;
    std::ifstream dataFile("file.txt");
    while (!dataFile.fail() && !dataFile.eof() )
    {
          dataFile >> name ;
          cout << name << endl;
    }
like image 35
Muhammad bakr Avatar answered Oct 12 '22 03:10

Muhammad bakr