Reading a text file - fopen vs. ifstream

user656925 picture user656925 · Jun 19, 2011 · Viewed 65.3k times · Source

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

Answer

Vinicius Kamakura picture Vinicius Kamakura · Jun 19, 2011

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