O'Reilly logo

C++ Primer Plus by Stephen Prata

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

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

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