If you use only cout, cerr, or clog, you don't have to worry about output stream construction. If you use file streams or string streams, then you must use constructors.
Output File Stream Constructors
If you need an output file stream, you have three choices:
You can use the void-argument constructor, then call the open member function.
ofstream myFile; // Static or on the stack
myFile.open( "filename", iosmode );
ofstream* pmyFile = new ofstream; // On the heap
pmyFile->open( "filename", iosmode );
You can specify a filename and mode flags in the constructor call, thereby opening the file during the construction process.
ofstream myFile( "filename", iosmode );
You can specify an integer file descriptor for a file that is already open for output. In this case you have the option to specify unbuffered output or a pointer to your own buffer.
int fd = _open( "filename", dosmode );
ofstream myFile1( fd ); // Buffered mode (default)
ofstream myFile2( fd, NULL, 0 ); // Unbuffered mode ofstream myFile3( fd, pch, buflen); // User-supplied buffer
For a description of how to use the mode flags of the open member function, see the Class Libraries Reference.
Output String Stream Constructors
There are two ostrstream constructors: one that dynamically allocates its own storage and one that requires the address and size of a preallocated buffer.
The dynamic constructor is used like this:
char* sp;
ostrstream myString << "this is a test" << ends;
sp = myString.str(); // Get a pointer to the string
The ends “manipulator” in this example adds a null terminator to the string. This terminator is necessary if the string is to be used by C run-time library functions that expect standard strings. For a description of manipulators, see “Format Control” on page 368.
The use of the “preallocation” constructor is demonstrated by the following example:
char s[32];
ostrstream myString( s, sizeof( s ) );
myString << "this is a test" << ends; // Text stored in s