Please enable JavaScript to use CodeHS

File I/O in C++

By David Burnham

As we start to use our programs to analyze more and more information, having a way to import and export information becomes critical. This is where file input and output become important. In this tutorial, we are going to look at a few things. First, we are going to take a look at how we read in lines from a file. We will then look at some very basic string manipulation to split our lines. Finally, we will look at how we can write out results to a file.

Reading in from a file

The basic work to read in from file is the following:

  • Create an input file stream and open the file
  • Loop through each line and read it in
    • After reading in the line, process the line
    • Move on to the next line
  • Break out of the loop at the end of the file

Let’s take a look at these steps below.

Notice in the example on line 19, we use the getline(in, line;) command. This is the line where we are actually reading from the file. The getline command can be used for other input streams as well, but in this context, we are calling it for a file stream. The first parameter is the input file stream to read from. The second parameter is where to put the input once it is read in. Notice that we create a string variable called line then pass that variable to out getline function. After calling getline, the next line from the file will be stored in the line variable. We can then process this line in any way that we like. In our example, we are printing out the value.

We continue this loop until there are no more lines to read. At that point, the in variable fails, and we can detect this and break out of our loop.

Basic string manipulation

Different files may contain different information and we may not just want each line to be its own string variable. The two most common things that we would need to do with a file input are splitting the line into pieces and transforming a string into a number. Below is an example, of how we might do this to sum lines of integer, but if you would like to see more details on both of these methods, check out the More String Functions in C++ tutorial (coming soon).

Output results to a file

Just as we can read in from a file, we can write out to a file. To read in, we opened an ifstream (in file stream). In contrast, to write out, we open an out file stream using ofstream. Once opened, we can stream output the same way we would stream to the console using <<.

One thing to note, in our system, you will not be able to see the output file, however you can open it as an input file and read in. Try it below! Try changing what is written to the output file and you will see this reflected when it is read back in.

Your turn to try

Now it is your turn to try! Read in the input file and add the value to a sum. Print out this sum each time you read in a new file. For example:

Running total = 4
Runnint total = 14
Running total = 17
...
Plain text