Using the Adapter Classes for Output
The first example of the Streams package’s adapter classes creates a RWStreambufToCharOutputStream object that connects to an instance of class RWCharToStreambufOutputStreamImp, which in turn uses an iostreams filebuf as a sink of narrow characters. The instance of the adapter class RWStreambufToCharOutputStream is used to construct an iostreams object of type ostream, which is used as the sink of data in the rest of the example.
Figure 17 is a representation of the chain of streaming elements used in this example.
Figure 17 – Streaming with adapter classes—output
The complete example is located in directory ...\examples\stream in the file adapterWrite.cpp. Only part of the code is presented below.
 
filebuf fbuf; // 1
fbuf.open("adaptorWrite.dat", ios::out);
 
RWCharOutputStream charOutputStream =
RWCharToStreambufOutputStreamImp::make(fbuf); // 2
 
RWStreambufToCharOutputStream streambufAdaptor(charOutputStream);// 3
 
ostream os(&streambufAdaptor); // 4
 
try {
double f= 3.14159;
int i= 567;
char* text="Wagabunga";
 
// insert a bunch of things
os << f << ' ' << i << ' ' << text; // 5
}
catch(const RWIncompleteStreamOperation& e) { // 6
cout << e.why() << endl;
cout << e.elementsProcessed() << endl;
}
catch(const RWExternalStreamException& e) {
cout << e.why() << endl;
}
//1 Creates an iostreams file buffer, and opens it in output mode. If you built the Advanced Tools Module with the Standard iostreams library, you need to qualify filebuf and other iostreams elements with std::, or you need to include using declarations. The complete example code makes use of macros defined by the Essential Tools Module in order to support both the classic and Standard iostreams.
//2 Creates an instance of class RWCharToStreambufOutputStreamImp. The class is created by calling its static member function make(), which creates an instance of self and returns it as a narrow character output stream handle. In this example the make() function takes a reference to an iostreams streambuf object that is used as the sink of bytes.
//3 Creates the adapter class that implements the iostreams streambuf interface and forwards request to an Advanced Tools Module narrow character output stream.
//4 Creates an iostreams ostream object that uses the previously created adapter class as the sink of narrow characters.
//5 Uses the ostream object.
//6 Catches exceptions potentially thrown by the stream. The Streams package defines two exception classes: RWExternalStreamException and RWIncompleteStreamOperation. Class RWExternalStreamException returns an error message and an error code. Class RWIncompleteStreamOperation inherits from class RWExternalStreamException, and is thrown when an operation partially succeeds. An instance of class RWIncompleteStreamOperation can be queried for the number of elements successfully written. For more information on exceptions, see Error Handling.