Example One: Simple Persisting Objects of Fundamental Type
This example uses simple persistence to save two integers to an output stream po, which saves the integers to the file int.dat. Then the example restores the two integers from the stream pi, which reads the integers from the file int.dat.
The example uses the overloaded insertion operator operator<< to save the objects, and the overloaded extraction operator operator>> to restore the objects, much the same way as you use these operators to output and input objects in C++ streams.
Note that the saving stream and the restoring stream are put into separate blocks. This is so that opening pi will cause it to be positioned at the beginning of the file.
Here is the code:
#include <assert.h>
#include <fstream>
#include <rw/pstream.h>
int main ()
{
int j1 = 1;
int k1 = 2;
// Save integers to the file "int.dat"
{
// Open the stream to save to:
std::ofstream f ("int.dat");
RWpostream pstr (f);
// Use overloaded insertion operator to save integers:
pstr << j1;
pstr << k1;
}
// Restore integers from the file "int.dat"
int j2 = 0;
int k2 = 0;
{
// Open a separate stream to restore from:
std::ifstream f ("int.dat");
RWpistream pstr (f);
// Use overloaded extraction operator to restore integers:
pstr >> j2; // j1 == j2
pstr >> k2; // k1 == k2
}
assert(j1 == j2);
assert(k1 == k2);
return 0;
}
The preceding example shows how easy it is to use overloaded operators to implement this level of persistence. So, what are some of the problems with using simple persistence? As mentioned above, one problem is that simple persistence will not maintain the pointer relationships among objects. We'll take a look at this problem in the next example.