O'Reilly logo

Essential C++ by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required