主函数用write和read的时候就能读取正常,单一个read就读取错误,这是为什么
#include
#include
using namespace std;
class Person{
public:
string name;
int age;
Person(string n,int a){
name = n;
age = a;
}
Person(){};
~Person(){};
void toString(){
cout<<"name:"<" age:"<void writeB(){
//导入头文件
//创建对象
ofstream ofs;
//打开文件,判断是否打开
ofs.open("e:\\a.txt",ios::out|ios::binary);
if(ofs.is_open()){
//写入文件
Person p("syx",19);
ofs.write((const char*)&p,sizeof (p));
} else{
cout<<"open file defluat"<//关闭流
ofs.close();
}
void readB(){
ifstream ifs;
ifs.open("e:\\a.txt",ios::in|ios::binary);
if(ifs.is_open()){
Person p;
ifs.read((char *)&p,sizeof (p));
p.toString();
} else{
cout<<"open file defluat"<close();
}
int main() {
writeB();
readB();
return 0;
}
writeB会生成这个文件。只是readB的话,如果这个文件不存,就报错了