Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a text file - fopen vs. ifstream

People also ask

Is Fopen faster than ifstream?

For some reason fstream is faster than fopen. on a 8192 byte buffer it's ~4.8 times faster.

Does ifstream read or write?

ifstream : Stream class to read from files. fstream : Stream class to both read and write from/to files.

How do I read a text file in C++?

Call open() method to open a file “tpoint. txt” to perform read operation using object newfile. If file is open then Declare a string “tp”. Read all data of file object newfile using getline() method and put it into the string tp.


Since this is tagged as C++, I will say ifstream. If it was tagged as C, i'd go with fopen :P


I would prefer ifstream because it is a bit more modular than fopen. Suppose you want the code that reads from the stream to also read from a string stream, or from any other istream. You could write it like this:

void file_reader()
{ 
    string line;
    ifstream myfile ("example.txt");
    if (myfile.is_open())
    {
        while (myfile.good())
        {
          stream_reader(myfile);
        }
        myfile.close();
    }
    else 
    {  
        cout << "Unable to open file"; 
    }
}

void stream_reader(istream& stream)
{
    getline (stream,line);
    cout << line << endl;
}

Now you can test stream_reader without using a real file, or use it to read from other input types. This is much more difficult with fopen.