basic_istream::gcount

To obtain the number of bytes read.

  streamsize gcount() const;
  
Remarks

Use the function gcount() to obtain the number of bytes read by the last unformatted input function called by that object.

Returns an int type count of the bytes read.

Listing: Example of basic_istream::gcount() usage:
#include <iostream>
#include <fstream>

const SIZE = 4;

struct stArray {

   int index;

   double dNum;

};

int main()

{ 

using namespace std;

   ofstream fOut("test");

   if(!fOut.is_open()) 

      {cout << "can't open out file"; return 1;}

   stArray arr;

   short i; 

   for(i = 1; i < SIZE+1; i++) 

   {

      arr.index = i;

      arr.dNum = i *3.14;

      fOut.write((char *) &arr, sizeof(stArray));

   }

   fOut.close();

   stArray aIn[SIZE];

   ifstream fIn("test");

   if(!fIn.is_open()) 

      {cout << "can't open in file"; return 2;}

   long count =0;

   for(i = 0; i < SIZE; i++) 

   {       fIn.read((char *) &aIn[i], sizeof(stArray));

   count+=fIn.gcount();

   }

   cout << count << " bytes read " << endl;

   cout << "The size of the structure is " 

      << sizeof(stArray) << endl;

   for(i = 0; i < SIZE; i++)

   cout << aIn[i].index << " " << aIn[i].dNum 

      << endl;

   fIn.close();

   return 0;

}

Result:

  48 bytes read 
  The size of the structure is 12
  1 3.14
  2 6.28
  3 9.42
  4 12.56