Use write() to output a block of binary data. - C++ File Stream

C++ examples for File Stream:Binary File

Description

Use write() to output a block of binary data.

Demo Code

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
// A simple Product structure.
struct Product {//from   www . j a  v a2s  . c  om
   char item[20];
   int quantity;
   double cost;
};
int main()
{
   // Create and open a file for binary output.
   ofstream fout("InvDat.dat", ios::out | ios::binary);
   // Confirm that the file opened without error.
   if(!fout) {
      cout << "Cannot open file.\n";
      return 1;
   }
   // Create some Product data.
   Product inv[3];
   strcpy(inv[0].item,"Hammers");
   inv[0].quantity = 3;
   inv[0].cost = 9.99;
   strcpy(inv[1].item, "Pliers");
   inv[1].quantity = 12;
   inv[1].cost = 7.85;
   strcpy(inv[2].item, "Wrenches");
   inv[2].quantity = 19;
   inv[2].cost = 2.75;
   // Write Product data to the file.
   for(int i=0; i<3; i++)
      fout.write((const char *) &inv[i], sizeof(Product));
   // Close the file.
   fout.close();
   // Confirm that there were no file errors.
   if(!fout.good()) {
      cout << "A file error occurred.";
      return 1;
   }
   return 0;
}

Related Tutorials