Use read() to read binary file. - C++ File Stream

C++ examples for File Stream:Binary File

Description

Use read() to read binary file.

Demo Code

#include <iostream>
#include <fstream>
using namespace std;
struct Product {// w w  w  .ja  v a 2 s.c  o  m
   char item[20];
   int quantity;
   double cost;
};
int main()
{
   // Open the file for binary input.
   ifstream fin("InvDat.dat", ios::in | ios::binary);
   // Confirm that the file opened without error.
   if(!fin) {
      cout << "Cannot open file.\n";
      return 1;
   }
   Product inv[3];
   // Read blocks of binary data.
   for(int i=0; i<3; i++)
      fin.read((char *) &inv[i], sizeof(Product));
   // Close the file.
   fin.close();
   // Confirm that there were no file errors.
   if(!fin.good()) {
      cout << "A file error occurred.\n";
      return 1;
   }
   // Display the Product data read from the file.
   for(int i=0; i < 3; i++) {
      cout << inv[i].item << "\n";
      cout << " Quantity on hand: " << inv[i].quantity;
      cout << "\n Cost: " << inv[i].cost << "\n\n";
   }
   return 0;
}

Result


Related Tutorials