Reading from a file in C++

Posted: 27th September 2010 by Tim in C++
Tags: , , , , , , , , ,

Reading data from a file is common in programming. C++ makes this process fairly painless with the ifstream class. When combined with the string class, you can avoid the memory and buffer overflow issues which you would have to deal with in C.

The following example opens a file named “myfile.txt” and prints out each line with the line number. Notice here that when reading the data, we check file.good() rather than file.eof() which you might see in other examples. file.good() checks for end of file and file errors which is much safer.

#include <fstream>  // for ifstream (input file stream)
#include <iostream> // for printing stuff to screen
#include <string>   // for the string object

int main (const int argc, const char **argv)
    // the file we want to read from
    std::string filename = "myfile.txt";

    // open the file
    std::ifstream file; (filename.c_str ());

    // make sure the file opened properly
    if (!file.is_open ())
        std::cerr << "Error opening file: "
                  << filename
                  << ". Aborting program."
                  << std::endl;
        return 1;

    // read each line and print it to the screen
    int lineCount = 0;
    std::string line;
    while (file.good ())
        // read a line from file and store it in line.
        std::getline (file, line);
        std::cout << ++lineCount
                  << ": "
                  << line
                  << std::endl;

    // make sure we close the file when we're finished.
    file.close ();

    return 0;