我剛剛開始使用二進制文件。我嘗試了一個簡單的程序:閱讀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名學生)只剩下最後學生的詳情。爲什麼?
我哪裏錯了?
既然你不顯示閱讀代碼誰可以說?你似乎認爲錯誤出現在編寫代碼中,但對我來說,這看起來或多或少。 – john
將對象轉儲爲二進制文件並將其讀回來是不安全的。您必須使用函數來單獨讀取/寫入字段。 –
@NeilKirk在某些有限的情況下是安全的,如果這些情況覆蓋了OP的課程,現在不能記得。 – john