[英]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.