我正在将对象的数据复制到文件流,然后,从同一个文件流中,我将该数据写入另一个对象,但它失败了。如果我创建另一个文件流,然后我执行相同的过程,它就可以工作。
非工作守则
struct customer
{
char name[23];
float balance;
};
main()
{
customer savac,s;
strcpy(savac.name,"Tina Marshall");
savac.balance=213123;
fstream fout("text.txt",ios::in|ios::out|ios::binary);
fout.write((char*)&savac,sizeof(customer));
fout.read((char*)&s,sizeof(customer));
cout<<s.name;
cout<<"\n"<<s.balance;
}
工作守则
struct customer
{
char name[23];
float balance;
};
main()
{
customer savac,s;
strcpy(savac.name,"Tina Marshall");
savac.balance=213123;
fstream fout("text.txt",ios::in|ios::out|ios::binary);
fout.write((char*)&savac,sizeof(customer));
fstream fin("text.txt");
fin.read((char*)&s,sizeof(customer));
cout<<s.name;
cout<<"\n"<<s.balance;
}