Simple Virtual Streams Example
Here is a simple example that exercises RWbostream and RWbistream through their respective abstract base classes, RWvostream and RWvistream:
 
#include <iostream>
#include <fstream>
#include <rw/bstream.h>
#include <rw/cstring.h>
 
void save (const RWCString& a, RWvostream& v)
{
// Save to the virtual output stream
v << a;
}
 
RWCString recover(RWvistream& v)
{
RWCString dupe;
 
// Restore from the virtual input stream
v >> dupe;
 
return dupe;
}
 
int main ()
{
RWCString a("A string with\ttabs and a\nnewline.");
RWCString b;
 
{
std::ofstream f("junk.dat", std::ios_base::out); // 1
RWbostream bostr(f); // 2
save(a, bostr);
} // 3
 
{
std::ifstream f ("junk.dat", std::ios_base::in); // 4
RWbistream bistr (f); // 5
b = recover (bistr); // 6
}
 
std::cout << "String sent to stream as: " << std::endl
<< "\t" << a << std::endl; // 7
 
std::cout << "String read from stream as: " << std::endl
<< "\t" << b << std::endl;
 
return 0;
}
Program Output:
 
String sent to stream as:
A string with tabs and a
newline.
String read from stream as:
A string with tabs and a
newline.
The job of function save(const RWCString& a, RWvostream& v) is to save the string a to the virtual output stream v. Function recover(RWvistream&) restores the results. These functions do not know the ultimate format with which the string will be stored. Here are some additional comments on particular lines:
//1 On this line, a file output stream f is created for the file junk.dat.
//2 An RWbostream is created from f.
//3 Because this clause is enclosed in braces { ... }, the destructor for f will be called here. This will cause the file to be closed.
//4 The file is reopened, this time for input.
//5 Now an RWbistream is created from it.
//6 The string is recovered from the file.
//7 Finally, both the original and recovered strings are printed for comparison.
You could simplify this program by using class fstream, which multiply inherits ofstream and ifstream, for both output and input. A seek to beginning-of-file would occur before reading the results back in. Since some early implementations of seekg() have not proven reliable, we chose not to use the simpler approach for this example.