18.2 Output Streams

An output stream object is a destination for bytes. The three most important output stream classes are ostream, ofstream, and ostrstream, as described below.

The ostream Class

The ostream class, through the derived class ostream_withassign, supports the predefined stream objects:

cout, standard output

cerr, standard error with limited buffering

clog, similar to cerr but with full buffering

You will rarely construct an object from class ostream (or from class ostream_withassign); you will generally use the predefined objects. Under certain circumstances, you may assign these standard names to other stream objects after program startup.

The ostream class is best suited to sequential text-mode output. All this chapter's formatting options apply to ostream objects, and these objects can be configured for buffered or unbuffered operation. All the functionality of the base class, ios, is included in ostream. See the Class Libraries Reference for details.

If you do construct an object of class ostream, then you must specify a streambuf object to the constructor. This is an advanced use of streams that is covered in “Deriving Your Own Stream Classes” in Chapter 19.

The ofstream Class

The ofstream class supports disk file output. Construct an object of class ofstream if you need an output-only disk file. You can specify whether ofstream objects accept binary or text-mode data. Indeed, you can change this mode after you have opened the file.

If you specify a filename in the constructor, that file is automatically opened when the object is constructed. Otherwise you can use the open member function after invoking the void-argument constructor, or you can construct an ofstream object based on an open file that is identified by a file descriptor.

Many formatting options and member functions apply to ofstream objects. All the functionality of the base classes ios and ostream is included in ofstream, and that includes the ability to open files in either buffered or unbufferd mode. See the iostream section of the Class Libraries Reference for details.

The ostrstream Class

The ostrstream class supports output to in-memory strings in a manner similar to the C run-time library function sprintf. When you need to create a string in memory using the I/O stream formatting facilities, construct an object of class ostrstream. Because ostrstream objects are write-only, your program must access the resulting string directly through a pointer to char.