Oracle® Solaris Studio 12.4: C++ User's Guide

Exit Print View

Updated: March 2015
 
 

13.10.2 Using streambuf Objects

You never create an actual streambuf object, but only objects of classes derived from class streambuf. Examples are filebuf and strstreambuf, which are described in the filebuf(3CC4) and ssbuf(3) man pages. Advanced users may want to derive their own classes from streambuf to provide an interface to a special device or to provide other than basic buffering. The sbufpub(3CC4) and sbufprot man pages (3CC4) discuss how to do this.

Apart from creating your own special kind of streambuf, you might want to access the streambuf associated with an iostream to access the public member functions, as described in the man pages. In addition, each iostream has a defined inserter and extractor which takes a streambuf pointer. When a streambuf is inserted or extracted, the entire stream is copied.

The following example shows another way to do the file copy discussed earlier, with the error checking omitted for clarity:

ifstream fromFile("thisFile");
ofstream toFile ("thatFile");
toFile << fromFile.rdbuf();

The input and output files are opened as before. Every iostream class has a member function rdbuf that returns a pointer to the streambuf object associated with it. In the case of an fstream, the streambuf object is type filebuf. The entire file associated with fromFile is copied (inserted into) the file associated with toFile. The last line could also be written as follows:

fromFile >> toFile.rdbuf();

The source file is then extracted into the destination. The two methods are entirely equivalent.