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:
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.