如何从 C++ 中的二进制文件中读取 class
How to read a class from binary file in c++
我有这段代码应该
- 从用户
读取数据到class对象
- 将该数据写入二进制文件
- 从二进制文件读取数据
显示给用户。
int main()
{
Bahd b; //Bahd is a class
cin>>b; //overloaded insertion operator
ofstream outfile("Data.bin",ios::out|ios::binary);
outfile.write(reinterpret_cast<char*>(&b),sizeof(b));
outfile.close();
ifstream infile("Data.bin",ios::in|ios::binary);
Bahd c;
infile.read(reinterpret_cast<char*>(&c),sizeof(c));
cout<<c;
}
但是当 运行 程序在输入数据后出现错误。
*** Error in `./a.out': munmap_chunk(): invalid pointer: 0x00007ffccbfbca50 ***
======= Backtrace: =========
/usr/lib/libc.so.6(+0x71e75)[0x7fdf6d79ae75]
/usr/lib/libc.so.6(+0x777c6)[0x7fdf6d7a07c6]
./a.out[0x401280]
./a.out[0x401156]
/usr/lib/libc.so.6(__libc_start_main+0xf0)[0x7fdf6d749610]
./a.out[0x400e69]
======= Memory map: ========
**more lines here**
Aborted (core dumped)
这是class
class Bahd{
private:
string name;
long acc_no;
long double bal;
public:
friend istream& operator >>(istream& src,Bahd& b);
friend ostream& operator <<(ostream& dest,Bahd& b);
};
我做错了什么?
您不能在 C++ 中对任何重要的 class 进行身份序列化(也就是说,假装您正在处理内存中的一些随机字节并四处移动这些字节)。而你的 class 中有一个 std::string
,这使得它非常重要 - 因为 std::string
是非常重要的。
相反,您应该适当地序列化它。
我有这段代码应该
- 从用户 读取数据到class对象
- 将该数据写入二进制文件
- 从二进制文件读取数据
显示给用户。
int main()
{
Bahd b; //Bahd is a class
cin>>b; //overloaded insertion operator
ofstream outfile("Data.bin",ios::out|ios::binary);
outfile.write(reinterpret_cast<char*>(&b),sizeof(b));
outfile.close();
ifstream infile("Data.bin",ios::in|ios::binary);
Bahd c;
infile.read(reinterpret_cast<char*>(&c),sizeof(c));
cout<<c;
}
但是当 运行 程序在输入数据后出现错误。
*** Error in `./a.out': munmap_chunk(): invalid pointer: 0x00007ffccbfbca50 ***
======= Backtrace: =========
/usr/lib/libc.so.6(+0x71e75)[0x7fdf6d79ae75]
/usr/lib/libc.so.6(+0x777c6)[0x7fdf6d7a07c6]
./a.out[0x401280]
./a.out[0x401156]
/usr/lib/libc.so.6(__libc_start_main+0xf0)[0x7fdf6d749610]
./a.out[0x400e69]
======= Memory map: ========
**more lines here**
Aborted (core dumped)
这是class
class Bahd{
private:
string name;
long acc_no;
long double bal;
public:
friend istream& operator >>(istream& src,Bahd& b);
friend ostream& operator <<(ostream& dest,Bahd& b);
};
我做错了什么?
您不能在 C++ 中对任何重要的 class 进行身份序列化(也就是说,假装您正在处理内存中的一些随机字节并四处移动这些字节)。而你的 class 中有一个 std::string
,这使得它非常重要 - 因为 std::string
是非常重要的。
相反,您应该适当地序列化它。