14.9 Writing Data Randomly to a Random-Access File
Figure 14.11 writes data to the file credit.dat and uses the combination of fstream functions seekp and write to store data at exact locations in the file. Function seekp sets the put file-position pointer to a specific position in the file, then function write outputs the data. Line 6 includes the header ClientData.h defined in Fig. 14.8, so the program can use ClientData objects.
14.9.1 Opening a File for Input and Output in Binary Mode
Line 10 uses the fstream object outCredit to open the existing credit.dat file. The file is opened for input and output in binary mode by combining the file-open modes ios::in, ios::out and ios::binary. Note that because we include ios::in, if the file does not exist, an error will occur and the file will not be opened. Opening the existing credit.dat file in this manner ensures that this program can manipulate the records written to the file by the program of Fig. 14.10, rather than creating the file from scratch.
14.9.2 Positioning the File-Position Pointer
Lines 39–40 position the put file-position pointer for object outCredit to the byte location calculated by
Because the account number is between 1 and 100, we subtract 1 from the account number when calculating the byte location of the record. Thus, for record 1, the file-position pointer is set to byte 0—the beginning of the file. For record 2, the the file-position pointer is set to 1 * sizeof(ClientData), and so on.