简体   繁体   中英

Reading Binary files in C++ 2

I had just started with binary files. I tried out a simple programme:

class student
{
    int rno;
    char sname[20];
    public:
    void input();
    void output();
};

void main() 
{
    clrscr();
    student s;
    char reply;
    fstream fil;

    fil.open("stu.dat",ios::binary|ios::app);
    do
    {
        s.input();
        fil.write((char*)&s,sizeof(s));
        cout<<"more (Y/N)\n";
        cin>>reply;
    }
    while(toupper(reply)=='Y');
    fil.close();
}

 void  student::input()
 {
 cout<<"enter the roll\n";
 cin>>rno;
 cout<<endl;
 cout<<"enter the name\n";
 gets(sname);
 cout<<endl;
 }

 void  student::output()  
 { 
 cout<<" the roll\n";
 cout<<rno;
 cout<<endl;
 cout<<"the name\n";
 puts(sname);
 cout<<endl;

But when i read this (say i have added 3 students) only last student's details are shown. why? Reading code:

  #include<fstream.h>
  #include<conio.h>
  #include<stdio.h>
  #include<ctype.h>

  class student
  {
  int rno;
  char sname[20];
  public:
  void input();
  void output();
  };

  void main()
  {
  clrscr();
  student s;
  fstream fil;
  fil.open("stu.dat",ios::binary|ios::in);

  while(fil.read((char*)&s,sizeof(s)));
  {
  s.output();
  getch();
  }
  fil.close();  
  }  

  void  student::input()
  {
  cout<<"enter the roll\n";
  cin>>rno;
  cout<<endl;
  cout<<"enter the name\n";
  gets(sname);
  cout<<endl;
  }

  void  student::output()
  {
  cout<<" the roll\n";
  cout<<rno;
  cout<<endl;
  cout<<"the name\n";
  puts(sname);
  cout<<endl;
  } 

But when i read this (say i have added 3 students) only last student's details are shown. why?

Where am i going wrong?

I'd suggest letting the student write itself to file

void student::Write( fstream & fil )
{
  fil.write((char*)&rno,sizeof( rno ));
  fil.write((char*)&sname,20);
}

This way, if your class attributes change you do not need to rewrite anything but the student implementation code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM