[英]Reading Binary files in C++ 2
我刚开始使用二进制文件。 我尝试了一个简单的程序:
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;
但是,当我阅读此内容(例如我添加了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 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;
}
但是,当我阅读此内容(例如我添加了3个学生)时,仅显示最后一个学生的详细信息。 为什么?
我要去哪里错了?
我建议让学生自己写文件
void student::Write( fstream & fil )
{
fil.write((char*)&rno,sizeof( rno ));
fil.write((char*)&sname,20);
}
这样,如果您的班级属性发生了变化,则除了学生实现代码外,您无需重写任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.