#include <iostream>
#include <fstream>
using namespace std;
class hi{
private:
string name;
string roll;
public:
void setName(string a){
this-> name = a;
}
string getName(){
return this-> name;
}
void setRoll(string a){
this-> roll = a;
}
string getRoll(){
return this-> roll;
}
};
int main(){
hi h;
string a ="Abdullah" ;
string b = "123123";
// opening is output mode
ofstream obj("a.dat", ios::binary | ios::app);
if(!obj){
cout << "error" << endl;
}
else{
h.setName(a);
h.setRoll(b);
obj.write(reinterpret_cast<char*>(&h), sizeof(h));
a += " saqib";
b += "456";
h.setName(a);
h.setRoll(b);
obj.write(reinterpret_cast<char*>(&h), sizeof(h));
obj.close();
}
// opening is input mode
ifstream obj1("a.dat", ios::binary | ios::in);
if(!obj1){
cout << "error" << endl;
}
else{
while(obj1.read(reinterpret_cast<char*>(&h), sizeof(h))){
cout << h.getName() << endl;
cout << h.getRoll() << endl;
}
obj1.close();
}
}
这是代码,问题是它第一次工作得很好但是当附加文件时它显示分段错误,我很困惑我做错了什么。
我也尝试过使用 char*,所以如果可以捕获 eof 的一些问题但失败了,我们将不胜感激:)