2.4.2 Reading in a File

The process of reading data from a file in C++ is similar to the process of reading data from the console. When you read data from the console, you essentially used the console stream as your input, then process the data. To read in data from a file, you replace that console stream with a file stream.

Creating an Input File Stream

Creating an input file stream is relatively straightforward in C++, but does require a few steps.

First, starting at the top of your program, you need to include fstream, the file stream library.

#include <fstream>

The fstream library is used for both input and output, but in this example you will be creating an input stream. To do that, you are going to create an input file stream using the variable type ifstream.

Start by declaring the variable, then use the open method to open a particular file. File names can be variables or string literals.

ifstream in;

in.open("openMe.txt");

In the example above, you create an input stream variable called in and use it to open the file named openMe.txt.

Unlike other languages such as Java, C++ does not require any error handling around opening a file. For now, you are going to add a check to print out if the file fails to load.

If the file does not load, your in variable will have a fail state that you can read:

if (in.fail())
    cout << "File didn't open"<<endl;

Reading From The File

Once the file stream has been opened, you are going to read each line of the file line by line. To do this, you use the same getline command you used to read in from the terminal. When reading in from the terminal, you specified cin as the input stream. Now you will specify the input stream variable as your input stream.

For example, if you use the in variable from about, you can read a line from the file with the following lines of code.

string line;
getline(in, line);

Recall how the getline command works. You pass an input stream and a variable and the getline command puts the next line from the input stream into that variable.

Reading In The Entire File

As mentioned above, when reading a file, you will read it line by line. The getline command above will help to read one line in, but to read an entire file you will need to loop through all the lines.

Since you don’t necessarily know how many lines are in the file, you will set up an infinite loop and then break out once there are no more lines. You will know that there are no more lines once your input stream fails.

Here is an example of a loop to process a file:

string line;
while (true) {
    getline(in, line);  
    if (in.fail()) break;

    // process line
}

Notice how the example uses a quick check for the fail state after reading in the line. If the file has no more lines, the input will fail and you will exit your loop. If it doesn’t fail, then you will have the next line in your line variable and can then process it as needed.

Last updated