Write and read object of class into and from binary file

前端 未结 4 1304
陌清茗
陌清茗 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条回答
  •  猫巷女王i
    2020-12-31 06:36

    The data is being buffered so it hasn't actually reached the file when you go to read it. Since you using two different objects to reference the in/out file, the OS has not clue how they are related.

    You need to either flush the file:

    mm.write(&out);
    out.flush()
    

    or close the file (which does an implicit flush):

    mm.write(&out); 
    out.close()
    

    You can also close the file by having the object go out of scope:

    int main()
    {
        myc mm(3);
    
        {
            ofstream out("/tmp/output");
            mm.write(&out); 
        }
    
        ...
    }
    

提交回复
热议问题