C++ imposes no structure on a file. Thus, a concept like that of a “record” does not exist in a C++ file. You must structure files to meet the application’s requirements. The following example shows how you can impose a simple record structure on a file.
Figure 14.3 creates a sequential file that might be used in an accounts-receivable system to help manage the money owed to a company by its credit clients. For each client, the program obtains the client’s account number, name and balance (i.e., the amount the client owes the company for goods and services received in the past). The data obtained for each client constitutes a record for that client. The account number serves as the record key; that is, the program creates and maintains the records of the file in account number order. This program assumes the user enters the records in account number order. In a comprehensive accounts receivable system, a sorting capability would be provided for the user to enter records in any order—the records then would be sorted and written to the file.
1 // Fig. 14.3: Fig14_03.cpp
2 // Create a sequential file.
3 #include <iostream>
4 #include <string>
5 #include <fstream> // contains file stream processing types
6 #include <cstdlib> // exit function prototype
7 using namespace std;
8
9 int main()
10 {
11 // ofstream constructor opens file
12 ofstream outClientFile( "clients.txt", ios::out );
13
14 // exit program if unable to create file
15 if ( !outClientFile ) // overloaded ! operator
16 {
17 cerr << "File could not be opened" << endl;
18 exit( EXIT_FAILURE );
19 } // end if
20
21 cout << "Enter the account, name, and balance." << endl
22 << "Enter end-of-file to end input.
? ";
23
24 int account; // the account number
25 string name; // the account owner's name
26 double balance; // the account balance
27
28 // read account, name and balance from cin, then place in file
29 while ( cin >> account >> name >> balance )
30 {
31 outClientFile << account << ' ' << name << ' ' << balance << endl;
32 cout << "? ";
33 } // end while
34 } // end main
Enter the account, name, and balance.
Enter end-of-file to end input.
? 100 Jones 24.98
? 200 Doe 345.67
? 300 White 0.00
? 400 Stone -42.16
? 500 Rich 224.62
? ^Z