/* lab10a.cpp 7/4/2005 CIS 150 David G. Klick Demonstrates writing structures to a binary file. */ #include #include #include using std::cout; using std::ofstream; using std::ios; struct Book { char title[40]; char author[35]; double price; int quantity; }; int main(void) { ofstream ofile; // used to handle output file // create a book object Book book1; // set fields in the book object strcpy(book1.title, "Designing CSS Web Pages"); strcpy(book1.author, "Schmitt, Christopher"); book1.price = 29.99; book1.quantity = 9; // create and set fields for a second book object Book book2 = { "CSS Cookbook", "Schmitt, Christopher", 34.95, 12 }; // create and set fields for a third book object Book book3 = { "Eric Meyer on CSS", "Meyer, Eric", 45.00, 10 }; // open random access file to write out books ofile.open("books.dat", ios::out | ios::binary); // display error if could not open file if (!ofile) { cout << "Error: Could not open output file!\n"; return 1; } // write book objects to file ofile.write((char*)&book1, sizeof(Book)); ofile.write((char*)&book2, sizeof(Book)); ofile.write((char*)&book3, sizeof(Book)); cout << "File created.\n"; // close file ofile.close(); return 0; }