c++fstreamdata-handling

How 7 is the right answer and not 6 in this output


Assume that the file SCHOOLS.DAT is created with the help of objects of class SCHOOLS, which is defined below: class SCHOOLS

class SCHOOLS
{
int SCode; // School Code
char SName[20]; // School Name
int NOT; // Number of Teachers in the school
public:
    void Display()
     {cout<<SCode<<"#"<<SName<<"#"<<NOT<<endl;}
      int RNOT(){return NOT;}
     };

Question Find the output of the following C++ code considering that the binary file SCHOOLS.DAT exists on the hard disk with the following records of 10 schools of the class SCHOOLS as declared in the previous .

SCode SName NOT

1001 Brains School 100

1003 Child Life School 115

1002 Care Share School 300

1006 Educate for Life School 50

1005 Guru Shishya Sadan 195

1004 Holy Education School 140

1010 Rahmat E Talim School 95

1008 Innovate Excel School 300

1011 Premier Education School 200

1012 Uplifted Minds School 100

void main()
{
 fstream SFIN;
 SFIN.open("SCHOOLS.DAT",ios::binary|ios::in);
 SCHOOLS S;
 SFIN.seekg(5*sizeof(S));
 SFIN.read((char*)&S, sizeof(S));
 S.Display();
 cout<<"Record :"<<SFIN.tellg()/sizeof(S) + 1<<endl;
 SFIN.close();
}

Output 1004#Holy Education School#140 Record :7

My Question How did Record is 7 and not 6.

My approach as the value of S will be 24 . Got it after adding the 2 byte of int Scode, 2 bytes of int NOT, 20 bytes of char SName[20].

so value of sizeof(S) will be 24 and value of SFIN.tellg will be 120 dividing them will give us 5 and then we have to add 1. So it will be 6 right?


Solution

  • You don't even need to think about the actual value of sizeof(S); just treat it as a constant K.

    You initially seek to the position 5*K. Then you read K bytes from the file, leaving you at the position 6*K. That means the expression SFIN.tellg()/sizeof(S) + 1 is equivilent to 6*K/K + 1. K/K is equal to 1 for any K, so that further simplifies to 6*1 + 1, which equals 7.