Hi
What is the difference between using the fstream library to read a file....and using something like a procedure below using the FILE* object?

There seems to be two ways to read a file?

Thanks

    /* FEOF example */
        #include <stdio.h>

        int main()
        {
           FILE * pFile;
           char buffer [100];

           pFile = fopen ("myfile.txt" , "r");
           if (pFile == NULL) perror ("Error opening file");
           else
           {
             while ( ! feof (pFile) )
             {
               if ( fgets (buffer , 100 , pFile) == NULL ) break;
               fputs (buffer , stdout);
             }
             fclose (pFile);
           }




   return 0;
}

The FILE* way of reading from a file is just the legacy that was inherited from C. The C++ language was developed with the aim of largely keeping compatibility with C (i.e., C is nearly a subset of C++, with only minor incompatibilities). This means that the entire C standard library is included in the C++ standard library, and in C++, they are preceeded with a "c", as in <cstdlib>, <cmath>, <cstdio>, etc... This is why there are a number of things that are repetitive. By and large, you should just try to stick to "real C++" libraries, like the iostream library.

Another example of that is all the string functionality which you have for C-style strings (char*) in the C <cstring> library, but you should prefer using the C++ string library <string> and the std::string class.

At this point (especially with C++11 additions), the only C library really worth using is <cmath>, which contains all those simple math functions like sine / cosine. Almost everything else has a better and easier-to-use equivalent in the C++ libraries.

And by the way, the code you posted is C code, not C++, although it is also valid C++ code (as I said, by compatibility). The C++ equivalent of that code is:

#include <iostream>
#include <fstream>
#include <string>

int main()
{

    std::ifstream file_in("myfile.txt");
    if( ! file_in.is_open() ) 
        std::cerr << "Error opening file" << std::endl;
    else
    {
        std::string buf;
        while( std::getline(file_in, buf) )
            std::cout << buf << std::endl;
    }

    return 0;
}

In terms of actual difference, I believe that the C-style file reading/writing has less buffering under-the-hood. However, this is not necessarily the case. All in all, there is no real difference in performance or whatever else, but, once you are used to doing C++, the C-style version seems archaic and ugly, like more C-style code.

Edited 3 Years Ago by mike_2000_17: added note

Comments
Very helpful answer.. Thanks

Thanks Mike. That is exactly what I was looking for. I really appreciate the C++ example you provided too.

This question has already been answered. Start a new discussion instead.