在c++ 2中读取二进制文件

Reading Binary files in C++ 2

本文关键字:读取 二进制文件 c++      更新时间:2023-10-16

我刚开始使用二进制文件。我试了一个简单的程序:

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 rolln";
 cin>>rno;
 cout<<endl;
 cout<<"enter the namen";
 gets(sname);
 cout<<endl;
 }
 void  student::output()  
 { 
 cout<<" the rolln";
 cout<<rno;
 cout<<endl;
 cout<<"the namen";
 puts(sname);
 cout<<endl;

但是当我读到这个(说我已经添加了3个学生)只有最后一个学生的详细信息显示。为什么?阅读代码:

  #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 rolln";
  cin>>rno;
  cout<<endl;
  cout<<"enter the namen";
  gets(sname);
  cout<<endl;
  }
  void  student::output()
  {
  cout<<" the rolln";
  cout<<rno;
  cout<<endl;
  cout<<"the namen";
  puts(sname);
  cout<<endl;
  } 

但是当我读到这个(说我已经添加了3个学生)只有最后一个学生的详细信息显示。为什么?

我哪里错了?

我建议让学生自己写文件

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

这样,如果你的类属性改变了,除了学生实现代码,你不需要重写任何东西。