read( ), write( ) and gcount( ): : File Read Write « File « C++






read( ), write( ) and gcount( ):

  
#include <iostream>
#include <fstream>
using namespace std;
   
int main()
{
  double fnum[4] = {99.75, -34.4, 1776.0, 200.1};
  int i;
   
  ofstream out("numbers", ios::out | ios::binary);
  if(!out) {
    cout << "Cannot open file.";
    return 1;
   }
   
  out.write((char *) &fnum, sizeof fnum);
   
  out.close();
   
  for(i=0; i<4; i++) // clear array
    fnum[i] = 0.0;
   
  ifstream in("numbers", ios::in | ios::binary);
  in.read((char *) &fnum, sizeof fnum);
   
  // see how many bytes have been read
  cout << in.gcount() << " bytes read\n";
   
  for(i=0; i<4; i++) // show values read from file
  cout << fnum[i] << " ";
   
  in.close();
   
  return 0;
}
  
    
  








Related examples in the same category

1.Reads information from the file and outputs it onto the screenReads information from the file and outputs it onto the screen
2.Another example of read() and write() and illustrates the use of gcount( )Another example of read() and write() and illustrates the use of gcount( )
3.Opening Files for Read and Write
4.Use get() and getline() to read characters.