How to read a class from binary file in c++ [duplicate]

不问归期 提交于 2019-12-11 13:44:00

问题


I have this code which is supposed to

  1. read data to class object from user
  2. Write that data to binary file
  3. Read data from binary file
  4. Display it to user.

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;
}
but I get error when running the program, at the point after inputting data.
*** 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)

Here is the 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);
    };

What wrong am I doing?


回答1:


You can not identity-serialize (that is, pretend you are dealing with some random bytes in memory and move those bytes around) any non-trivial class in C++. And your class has an std::string in it, which makes it non-trivial - since std::string is non-trivial.

Instead, you should proprely serialize it.



来源:https://stackoverflow.com/questions/35701974/how-to-read-a-class-from-binary-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!