抛出C ++异常:读取访问冲突(fopen / fread struct)

时间:2016-10-24 16:08:03

标签: c++ struct fopen fread

这是我的结构:

struct Account {
string accID;
string name;
float balance;
string currency;
int status; 
};

功能:

Account layFileTaiKhoan(string id) {
FILE * openfile;
Account getAcc;
string mypath = "Account\\" + id + ".dat";
openfile = fopen(mypath.c_str(), "r");

fread(&getAcc, sizeof TaiKhoan, 1, openfile);

fclose(openfile);

return getAcc;
}

但是我收到了这个错误:“抛出异常:读取访问冲突”当使用我的函数将结构保存在.dat文件中时。

请帮我解决这个错误,非常感谢你的帮助!

1 个答案:

答案 0 :(得分:4)

您不能fread一个std::string(或包含std::string的对象),因为std::string对象只包含指向实际字符串的指针(简称除外)带有一些库实现的字符串。)读取先前编写的指针是没有意义的,使用指针是Undefined Behavior。