In the previous sections, we created a random-access file and wrote data to that file. In this section, we develop a program that reads the file sequentially and prints only those records that contain data. These programs produce an additional benefit. See if you can determine what it is; we’ll reveal it at the end of this section.
The istream
function read
inputs a specified number of bytes from the current position in the stream into an object. For example, line 28 (Fig. 14.12) reads the number of sizeof(ClientData)
bytes from the file associated with inCredit
and stores the data in client
. Function read
requires a first argument of type char
*. Since &client
is of type ClientData
*, &client
must be cast to char
* using the cast operator reinterpret_cast
.
Figure 14.12 reads every record in the credit.dat
file sequentially, checks each record to determine whether it contains data, and displays formatted outputs for records containing data. The condition in line 31 implicitly uses the stream’s operator bool
to determine whether the end of file was reached or whether an error occurred when reading from the file—in both cases the while
statement terminates. The data input from the file is output by function outputLine
(lines 43–49), which takes two arguments—a reference to an ostream
object and a clientData
structure to be output. The ostream
parameter type is interesting, because any ostream
object (such as cout
) or any object of a derived class of ostream
(such as an object of type ofstream
) can be supplied as the argument. This means that the same function can be used, for example, to perform output to the standard-output stream and to a file stream without writing separate functions.
What about that additional benefit we promised at the beginning of this section? If you examine the output window, you’ll notice that the records are listed in sorted order (by account number). This is a consequence of how we stored these records in the file, using direct-access techniques. Sorting using direct-access techniques is relatively fast. The speed is achieved by making the file large enough to hold every possible record that might be created. This, of course, means that the file could be occupied sparsely most of the time, resulting in a waste of storage. This is an example of the space-time trade-off: By using large amounts of space, we can develop a much faster sorting algorithm. Fortunately, the continuous reduction in price of storage units has made this less of an issue.