Search code examples
c++filefopenifstream

Reading a text file - fopen vs. ifstream


Googling file input I found two ways to input text from a file - fopen and ifstream. Below are the two snippets. I have a text file consisting of one line with an integer I need to read in. Should I use fopen or ifstream?

SNIPPET 1 - FOPEN

FILE * pFile = fopen ("myfile.txt" , "r");
char mystring [100];
if (pFile == NULL) 
{
    perror ("Error opening file");
}
else 
{
    fgets (mystring , 100 , pFile);
    puts (mystring);
    fclose (pFile);
}

SNIPPET 2 - IFSTREAM

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

Solution

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