Chapter 7. Using Class RWFile

Class RWFile encapsulates the standard C file operations for binary read and write, using the ANSI-C functions fopen(), fwrite(), fread(), etc. This class is patterned on class PFile of the Interviews Class Library (Stanford University, 1987), but has been modernized by Rogue Wave to use const modifiers, and to port to various operating systems. The member function names begin with upper case letters in order to maintain compatibility with class PFile.

The constructor for class RWFile has the prototype:

RWFile(const char* filename, const char* mode = 0);

This constructor will open or create a binary file called filename with mode set to mode (for example, r+), as defined by the Standard C function fopen(). If mode is zero, which is the default, an existing file will be opened for update (mode r+ for UNIX, rb+ for Windows environments). If filename does not exist, it will be created (mode w+ for UNIX, wb+ for Windows environments). The destructor for this class closes the file.

After constructing an RWFile, you should use member function isValid() to check whether opening the file was successful.

There are member functions to flush the file, and to test whether the file has had an error, or is empty or at the end-of-file.

Example

Class RWFile also has member functions to determine the status of a file, and to read and write a wide variety of built-in types, either one at a time, or as arrays. The file pointer may be repositioned with functions SeekTo(), SeekToBegin(), and SeekToEnd(). The details of the RWFile class capabilities are summarized in the Class Reference.

The following example creates an RWFile with filename test.dat. The code reads an int (if the file is not empty), increments it, and writes it back to the file:

#include <rw/rwfile.h>
main(){
   RWFile file("test.dat");               // Construct the RWFile.
   // Check that the file exists, and that it has 
   // read/write permission:
   if ( file.Exists() )
{
     int i = 0;
     // Read the int if the file is not empty:
     if ( !file.IsEmpty() ) file.Read(i);
     i++;
     file.SeekToBegin();
     file.Write(i);                            // Rewrite the int.
   }
   return 0;
}