//This program demonstrates the use of a structure variable to //store a record of information to a file. #include #include #include // for toupper using namespace std; const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14; // Declare a structure for the record struct Info { char name[NAME_SIZE]; int age; char address1[ADDR_SIZE]; char address2[ADDR_SIZE]; char phone[PHONE_SIZE]; }; int main() { Info person; // Store information about a person char response; // User response // Create file object and open file. fstream people("people.dat", ios::out | ios::binary); if (!people) { cout << "Error opening file. Program aborting.\n"; return 0; } // Keep getting information from user and writing it // to the file in binary mode. do { cout << "Enter the following information about a person:\n"; cout << "Name: "; cin.getline(person.name, NAME_SIZE); cout << "Age: "; cin >> person.age; cin.ignore(); // Skip over remaining newline. cout << "Address line 1: "; cin.getline(person.address1, ADDR_SIZE); cout << "Address line 2: "; cin.getline(person.address2, ADDR_SIZE); cout << "Phone: "; cin.getline(person.phone, PHONE_SIZE); people.write(reinterpret_cast(&person), sizeof(person)); // people.write((char *)&person, sizeof(person)); //older method of type casting cout << "Do you want to enter another record? "; cin >> response; cin.ignore(); } while (toupper(response) == 'Y'); // Close file. people.close(); // Open file for binary reading. people.open("people.dat", ios::in | ios::binary); if (!people) { cout << "Error opening file. Program aborting.\n"; return 0; } // Label the output. cout << "Here are the people in the file:\n\n"; // Read one structure at a time and echo to screen. people.read(reinterpret_cast(&person), sizeof(person)); // people.read((char *)&person, sizeof(person)); //older method of type casting while (!people.eof()) { cout << "Name: "; cout << person.name << endl; cout << "Age: "; cout << person.age << endl; cout << "Address line 1: "; cout << person.address1 << endl; cout << "Address line 2: "; cout << person.address2 << endl; cout << "Phone: "; cout << person.phone << endl; cout << "\nStrike any key to see the next record.\n"; cin.get(response); people.read(reinterpret_cast(&person), sizeof(person)); // people.read((char *)&person, sizeof(person)); //older method of type casting } cout << "That's all the information in the file!\n"; // Close file. people.close(); return 0; }