Rogue Wave banner
Previous fileTop of documentContentsIndexNext file

6.2 Simple Example

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/cstring.h>
#include <fstream.h>

#ifdef __BORLANDC__
# define MODE ios::binary                                    // 1
#else
# define MODE 0
#endif

void save(const RWCString& a, RWvostream& v){
  v << a;                    // Save to the virtual output stream
}

RWCString recover(RWvistream& v) {
   RWCString dupe;
   v >> dupe;            // Restore from the virtual input stream
   return dupe;
}

main(){
   RWCString a("A string with\ttabs and a\nnewline.");

   {
     ofstream f("junk.dat", ios::out|MODE);                  // 2
     RWbostream bostr(f);                                    // 3
     save(a, bostr);
   }                                                         // 4

   ifstream f("junk.dat", ios::in|MODE);                     // 5
   RWbistream bistr(f);                                      // 6
   RWCString b = recover(bistr);                             // 7

   cout << a << endl;  // Compare the two strings            // 8
   cout << b << endl;
   return 0;
}

Program Output:

A string with   tabs and a
newline.
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-//2On these lines, a file output stream f is created for the file junk.dat. The default file open mode for many PC compilers is text, requiring that the explicit flag ios::binary be used to avoid automatic DOS new line conversion[6].
//3On this line, an RWbostream is created from f.
//4Because this clause is enclosed in braces { ... }, the destructor for f will be called here. This will cause the file to be closed.
//5The file is reopened, this time for input.
//6Now an RWbistream is created from it.
//7The string is recovered from the file.
//8Finally, 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, the simpler approach was not chosen for this example.


Previous fileTop of documentContentsIndexNext file
©Copyright 1999, Rogue Wave Software, Inc.
Send mail to report errors or comment on the documentation.