If you use only the predefined cout, cerr, or clog objects, you don’t need to construct an output stream. You must use constructors for:
You can construct an output file stream in one of three ways:
ofstream myFile; // Static or on the stack
myFile.open( "filename", iosmode );
ofstream* pmyFile = new ofstream; // On the heap
pmyFile->open( "filename", iosmode );
ofstream myFile( "filename", iosmode );
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
To construct an output string stream, you can use one of two ostrstream constructors. One dynamically allocates its own storage, and the other requires the address and size of a preallocated buffer.
char* sp;
ostrstream myString;
mystring << "this is a test" << ends;
sp = myString.str(); // Get a pointer to the string
The ends “manipulator” adds the necessary terminating null character to the string.
char s[32];
ostrstream myString( s, sizeof( s ) );
myString << "this is a test" << ends; // Text stored in s