Simple File I/O

Suppose you want a program to write to a file. You must do the following:

1. Create an ofstream object to manage the output stream.

2. Associate that object with a particular file.

3. Use the object the same way you would use cout; the only difference is that output goes to the file instead of to the screen.

To accomplish this, you begin by including the fstream header file. Including this file automatically includes the iostream file for most, but not all, implementations, so you may not have to include iostream explicitly. Then you declare an ofstream object:

ofstream fout;      // create an ofstream object named fout

The object’s name can be any valid C++ name, such as fout, outFile, cgate, or didi.

Next, you must associate ...

Get C++ Primer Plus 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.