将对象以二进制写入文件读取时为和最后一条会多读一次

来源:百度知道 编辑:UC知道 时间:2024/05/23 20:37:23
、、读的代码
CHotel hotel;
ifstream infile;
infile.open("Hotel.dat",ios::binary|ios::in|ios::nocreate);

while(!infile.eof())
{
infile.read((char*)&hotel,sizeof(hotel));
//infile>>hotel;
cout<<hotel.GetnumDelRoom()<<" ";
}
、、写的代码
ofstream outfile;
outfile.open("Hotel.dat",ios::binary);
outfile.write((char *)this,sizeof(*this));
outfile.close();

不明白你写的时候为什么要做转换,写的字节数的多少,看上去也是怪怪的
outfile.write((char *)this,sizeof(*this));
能不能直接写:
outfile.write(something,sizeof(something));
读的字节数的多少看上去也是怪怪的
能不能直接写:
infile.read(&hotel,sizeof(hotel));

读写二进制文件的关键是字节数(读写多少个bytes)。sizeof自动计算变量实际使用的字节数。