In Fig. 14.11, line 11 creates an ofstream
object for the file credit.dat
. The second argument to the constructor—ios::out
| ios::binary—indicates that we are opening the file for output in binary mode, which is required if we are to write fixed-length records. Multiple file-open modes are combined by separating each open mode from the next with the |
operator, which is known as the bitwise inclusive OR operator. (Chapter 20 discusses this operator in detail.) Lines 24–25 cause the blankClient
(which was constructed with default arguments at line 20) to be written to the credit.dat
file associated with ofstream
object outCredit
. Remember that operator sizeof
returns the size in bytes of the object contained in parentheses (see Chapter 8). The first argument to function write
at line 24 must be of type const char *
. However, the data type of &blankClient
is ClientData *
. To convert &blankClient
to const char *
, line 24 uses the cast operator reinterpret_cast
, so the call to write
compiles without issuing a compilation error.
1 // Fig. 14.11: Fig14_11.cpp
2 // Creating a randomly accessed file.
3 #include <iostream>
4 #include <fstream>
5 #include <cstdlib>
6 #include "ClientData.h" // ClientData class definition
7 using namespace std;
8
9 int main()
10 {
11 ofstream outCredit( "credit.dat", ios::out | ios::binary );
12
13 // exit program if ofstream could not open file
14 if ( !outCredit )
15 {
16 cerr << "File could not be opened." << endl;
17 exit( EXIT_FAILURE );
18 } // end if
19
20 ClientData blankClient; // constructor zeros out each data member
21
22 // output 100 blank records to file
23 for ( int i = 0; i < 100; ++i )
24 outCredit.write( reinterpret_cast< const char * >( &blankClient ),
25 sizeof( ClientData ) );
26 } // end main