Files store data so it may be retrieved for processing when needed. The previous section demonstrated how to create a file for sequential access. We now discuss how to read data sequentially from a file. Figure 14.6 reads and displays the records from the clients.txt
file that we created using the program of Fig. 14.3. Creating an ifstream
object opens a file for input. The ifstream
constructor can receive the filename and the file open mode as arguments. Line 15 creates an ifstream
object called inClientFile
and associates it with the clients.txt
file. The arguments in parentheses are passed to the ifstream
constructor, which opens the file and establishes a “line of communication” with the file.
1 // Fig. 14.6: Fig14_06.cpp
2 // Reading and printing a sequential file.
3 #include <iostream>
4 #include <fstream> // file stream
5 #include <iomanip>
6 #include <string>
7 #include <cstdlib>
8 using namespace std;
9
10 void outputLine( int, const string &, double ); // prototype
11
12 int main()
13 {
14 // ifstream constructor opens the file
15 ifstream inClientFile( "clients.txt", ios::in );
16
17 // exit program if ifstream could not open file
18 if ( !inClientFile )
19 {
20 cerr << "File could not be opened" << endl;
21 exit( EXIT_FAILURE );
22 } // end if
23
24 int account; // the account number
25 string name; // the account owner's name
26 double balance; // the account balance
27
28 cout << left << setw( 10 ) << "Account" << setw( 13 )
29 << "Name" << "Balance" << endl << fixed << showpoint;
30
31 // display each record in file
32 while ( inClientFile >> account >> name >> balance )
33 outputLine( account, name, balance );
34 } // end main
35
36 // display single record from file
37 void outputLine( int account, const string &name, double balance )
38 {
39 cout << left << setw( 10 ) << account << setw( 13 ) << name
40 << setw( 7 ) << setprecision( 2 ) << right << balance << endl;
41 } // end function outputLine
Account Name Balance
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62
Good Programming Practice 14.1
If a file’s contents should not be modified, use ios::in to open it only for input. This prevents unintentional modification of the file’s contents and is another example of the principle of least privilege.