SourcePro : Essential Math Module User’s Guide : Persistence : A Simple Example Using Streams
A Simple Example Using Streams
Here’s a simple example that exercises RWbostream and RWbistream through their respective abstract base classes, RWvostream and RWvistream:
 
#include <rw/bstream.h>
#include <rw/math/mathvec.h>
#include <fstream.h>
 
template<class T>
void save(RWMathVec<T>& a, RWvostream& v)
{
a.saveOn(v); // Save to virtual output stream
}
 
template<class T>
RWMathVec<T> recover(RWvistream& v)
{
RWMathVec<T> dupe;
dupe.restoreFrom(v);
return dupe;
}
 
int main()
{
RWMathVec<double> a(10, 0.0, 2.0); // 0, 2, 4, ..., 18
{
ofstream f("junk.dat", ios::out); // 1
RWbostream bostr(f); // 2
save(a, bostr);
} // 3
ifstream f("junk.dat", ios::in); // 4
RWbistream bistr(f); // 5
RWMathVec<double> b = recover(bistr); // 6
cout << a << endl; // Compare the vectors // 7
cout << b << endl;
}
 
Program output:
[
0 2 4 6 8
10 12 14 16 18
]
[
0 2 4 6 8
10 12 14 16 18
]
 
The job of function save(RWMathVec<T>& a, RWvostream& v) is to save the vector a to the virtual output stream v. Function recover(RWvistream&) restores the results. These functions do not know the ultimate format with which the vector will be stored, although in this case it will be in binary format because the specializing classes are RWbostream and RWbistream. 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 On this line, an RWbostream is created from f.
//3 Because this clause is enclosed in braces { ... }, the destructor for f is called here. This causes the file to be closed.
//4 The file is reopened, this time for input.
//5 Now an RWbistream is created from it.
//6 The vector is recovered from the file.
//7 Finally, both the original and recovered vectors are printed for comparison.