Output Streams

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

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

Objects are rarely constructed from ostream or ostream_withassign; predefined objects are generally used. In some cases, you can reassign predefined objects after program startup. The ostream class, which can be configured for buffered or unbuffered operation, is best suited to sequential text-mode output. All functionality of the base class, ios, is included in ostream. If you construct an object of class ostream, you must specify a streambuf object to the constructor.

The ofstream class supports disk file output. If you need an output-only disk, construct an object of class ofstream. You can specify whether ofstream objects accept binary or text-mode data before or after opening the file. Many formatting options and member functions apply to ofstream objects, and all functionality of the base classes ios and ostream is included.

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 default constructor, or you can construct an ofstream object based on an open file that is identified by a file descriptor.

Like the run-time function sprintf, the ostrstream class supports output to in-memory strings. To create a string in memory using I/O stream formatting, construct an object of class ostrstream. Because ostrstream objects are write-only, your program must access the resulting string through a pointer to char.