-1
#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;

class Student{
private:
    char name[40];
    char grade;
    float marks;
public:
    void getdata();
    void display();
};

void Student::getdata(){
    char ch;
    cin.get(ch);
    cout<<"Enter name : ";
    cin.getline(name,40);
    cout<<"Enter grade : ";
    cin>>grade;
    cout<<"Enter marks : ";
    cin>>marks;
    cout<<"\n";
}

void Student::display(){
    cout<<"Name : "<<name<<"\t";
    cout<<"Grade : "<<grade<<"\t";
    cout<<"Marks : "<<marks<<"\t"<<"\n";
}

int main(){
    system("cls");
    Student arts[3];
    fstream f;
    f.open("stu.txt",ios::in|ios::out|ios::binary);
    if(!f){
        cerr<<"Cannot open file !";
        return 1;
    }
    for(int i=0;i<3;i++){
        arts[i].getdata();
        f.write((char*)&arts[i],sizeof(arts[i]));
    }
    f.seekg(0); //The question is about this statement;
    cout<<"The contents of stu.txt are shown below : \n";
    for(int j=0;j<3;j++){
        f.read((char*)&arts[j],sizeof(arts[j]));
        arts[j].display();
    }
    f.close();
    return 0;
}

The above program reads and writes objects of Student from/to the file "stu.txt". It runs fine. But it runs fine even if I switch off the fin.seekg(0) statement. I don't understand this part ? Are we not supposed to set the file pointer to the beginning of the file - before starting to read objects from the file(in the context of this particular program)?.

Monk
  • 181
  • 1
  • 3
  • 11

1 Answers1

3

If you are at the end of the file, the read method call will fail, thus the Student structures are left untouched (so you are just printing again the same structures which you left untouched after writing them to file).

pqnet
  • 6,070
  • 1
  • 30
  • 51
  • Thanks, I understand now - I created a new array of objects and tried to switch off fin.seekg(0) - and it did print all garbage ! – Monk Sep 08 '14 at 16:04