Write numbers to a binary file and read them back : Binary File « File « C++






Write numbers to a binary file and read them back

  
#include <iostream>
#include <fstream>
using namespace std;
int main(void){
   float fnum[4] = {11.22, -33.44, 55.66, 77.88};
   int i;

   ofstream out("numbers.asc", ios::out | ios::binary);
   if(!out){
      cout << "Cannot open file.";
      exit (1);
   }
   out.write((char *) &fnum, sizeof(fnum));
   out.close();
   for (i=0; i<4; i++)
      fnum[i] = 0.0;
   ifstream in("numbers.asc", ios::in | ios::binary);
   if(!in) {
      cout << "Cannot open file.";
      exit (1);
   }
   in.read((char *) &fnum, sizeof(fnum));
   cout << in.gcount() << " bytes read." << endl;
   for (i=0; i<4; i++)
      cout << fnum[i] << " ";
   in.close();
}
  
    
  








Related examples in the same category

1.reading a complete binary file
2.Binary Files
3.seeks particular person in file
4.binary input and output with integers