/* lab10b.cpp 7/4/2005 CIS 150 David G. Klick Demonstrates reading structures from a binary file. */ #include #include #include #include using std::cout; using std::ifstream; using std::ofstream; using std::ios; using std::setw; using std::setprecision; using std::showpoint; using std::fixed; struct Book { char title[40]; char author[35]; double price; int quantity; }; void display(Book b); int main(void) { ifstream ifile; // used to handle input file long numrecs; // create three book objects Book book1, book2, book3; // open random access file to read in books ifile.open("books.dat", ios::in | ios::binary); // display error if could not open file if (!ifile) { cout << "Error: Could not open input file!\n"; return 1; } // find out how many records are in file ifile.seekg(0L, ios::end); // go to end of file numrecs = ifile.tellg() / sizeof(Book); ifile.seekg(0L, ios::beg); // go to start of file // display error if not three books in file if (numrecs != 3) { cout << "Error: " << numrecs << " books in file.\n"; return 2; } // read book objects from file ifile.read((char*)&book1, sizeof(Book)); ifile.read((char*)&book2, sizeof(Book)); ifile.read((char*)&book3, sizeof(Book)); // close file ifile.close(); // display book info read from file cout << "Book information read from file:\n "; display(book1); cout << "\n "; display(book2); cout << "\n "; display(book3); cout << '\n'; return 0; } void display(Book b) { cout << b.title << ", by " << b.author << " (" << b.quantity << " @ $" << fixed << showpoint << setprecision(2) << b.price << ')'; }