// Use random-access I/O to read specific inventory records
// from a data file. This program reads the file InvDat.dat,
// which is created by the example program in the recipe:
//
// Write Unformatted Binary Data to a File
#include <iostream>
#include <fstream>
#include <cstdlib>
usingnamespace std;
// A simple inventory structure.
struct inventory {
char item[20];
int quantity;
double cost;
};
int main(int argc, char *argv[])
{
inventory entry;
long record_num;
if(argc != 2) {
cout << "Usage: ShowRecord <record-num>\n";
return 1;
}
// Convert the string representation of the entry
// number into a long value.
record_num = atol(argv[1]);
// Confirm that the record number is greater than or
// equal to zero.
if(record_num < 0) {
cout << "Record numbers must be greater than or equal to 0.\n";
return 1;
}
// Open the file for binary input.
ifstream fInvDB("InvDat.dat", ios::in | ios::binary);
// Confirm that the file opened without error.
if(!fInvDB) {
cout << "Cannot open file.\n";
return 1;
}
// Read and display the entry specified on the command line.
// First, seek to the desired record.
fInvDB.seekg(sizeof(inventory) * record_num, ios::beg);
// Next, read the record.
fInvDB.read((char *) &entry, sizeof(inventory));
// Close the file.
fInvDB.close();
// Confirm that there were no file errors.
if(!fInvDB.good()) {
cout << "A file error occurred.\n";
return 1;
}
// Display the inventory for the specified entry.
cout << entry.item << endl;
cout << "Quantity on hand: " << entry.quantity;
cout << "\nCost: " << entry.cost << endl;
return 0;
}
After going through data to set the pointer in the front of the requested record