/* lab11.cpp 7/4/2005 CIS 150 David G. Klick Demonstrates reading structures from a binary file and then sorting them. */ #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; const int MAX_ARRAY_SIZE = 10; struct Book { char title[40]; char author[35]; double price; int quantity; }; void display(Book b); void sortByAuthor(Book b[], int len); void sortByPrice(Book b[], int len); void sortByQuantity(Book b[], int len); void sortByTitle(Book b[], int len); int main(void) { ifstream ifile; // used to handle input file long numrecs; int booksInArray; int i; // create array of book objects Book books[MAX_ARRAY_SIZE]; // 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 more books than array can hold if (numrecs > MAX_ARRAY_SIZE) { cout << "Error: Too many records in file.\n"; return 2; } // read book objects from file for (i=0; i 0) { temp = b[i]; b[i] = b[j]; b[j] = temp; } } } } void sortByPrice(Book b[], int len) { int i, j; Book temp; for (i=0; i b[j].price) { temp = b[i]; b[i] = b[j]; b[j] = temp; } } } } void sortByQuantity(Book b[], int len) { int i, j; Book temp; for (i=0; i b[j].quantity) { temp = b[i]; b[i] = b[j]; b[j] = temp; } } } } void sortByTitle(Book b[], int len) { int i, j; Book temp; for (i=0; i 0) { temp = b[i]; b[i] = b[j]; b[j] = temp; } } } }