Write and read object of class into and from binary file

前端 未结 4 1276
陌清茗
陌清茗 2020-12-31 05:51

I try to write and read object of class into and from binary file in C++. I want to not write the data member individually but write the whole object at one time. For a simp

4条回答
  •  迷失自我
    2020-12-31 06:23

    I'll echo "you shouldn't be doing this". If you print out sizeof(myc) in the code above it's probably 4, as you'd expect... BUT try changing read and write to be virtual. When I did so, it prints out the size as 16. Those 12 bytes are internal guts with sensitive values—and saving them out and then reading them back in would be like expecting a pointer value to be still good if you wrote it and loaded it again.

    If you want to circumvent serialization and map C++ object memory directly to disk, there are ways to hack that. But rules are involved and it's not for the faint of heart. See POST++ (Persistent Object Storage for C++) as an example.

    I'll add that you did not check the fail() or eof() status. If you had you'd have known you were misusing the fstream API. Try it again with:

    void read(ifstream *in) {
        in->read((char *) this, sizeof(myc));
        if (in->fail())
            cout << "read failed" << endl;
    }
    void write(ofstream *out){
        out->write((char *) this, sizeof(myc));
        if (out->fail())
            cout << "write failed" << endl;
    }
    

    ...and see what happens.

提交回复
热议问题