1.7. Writing and Reading Files

If a user should happen to run our program a second time, it would be nice to allow her score to reflect both sessions. To do this, we must (1) write the user’s name and session data to a file at the end of the session and (2) read the user’s session data back into the program at the start of the next session. Let’s see how we might do that.

To read and write to a file, we must include the fstream header file:

#include <fstream> 

To open a file for output, we define an ofstream (an output file stream) class object, passing it the name of the file to open:

// seq_data.txt is opened in output mode 
ofstream outfile( "seq_data.txt" ); 

What happens when we declare outfile? If it doesn’t exist, the file is created ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.