Using random-access I/O to read specific records from a data file. - C++ File Stream

C++ examples for File Stream:File Operation

Description

Using random-access I/O to read specific records from a data file.

Demo Code

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

struct Product {// w  w w.  j  ava2 s .c  o  m
   char item[20];
   int quantity;
   double cost;
};
int main(int argc, char *argv[])
{
   Product entry;
   long record_num;
   record_num = 2;
   // 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(Product) * record_num, ios::beg);
   // Next, read the record.

   fInvDB.read((char *) &entry, sizeof(Product));
   // 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 Product for the specified entry.
   cout << entry.item << endl;
   cout << "Quantity on hand: " << entry.quantity;
   cout << "\nCost: " << entry.cost << endl;
   return 0;
}

Result


Related Tutorials