向二进制文件中写入和读取类的对象 [英] Write and read object of class into and from binary file

查看:119
本文介绍了向二进制文件中写入和读取类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在C ++中的二进制文件中写入和读取类的对象。我想不单独写入数据成员,但一次写入整个对象。一个简单的例子:

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 simple example:

class MyClass {  
public:  
     int i;  

     MyClass(int n) : i(n) {}   
     MyClass() {}  

     void read(ifstream *in)  { in->read((char *) this, sizeof(MyClass));  }  
     void write(ofstream *out){ out->write((char *) this, sizeof(MyClass));}  
};  

int main(int argc, char * argv[]) {  
     ofstream out("/tmp/output");  
     ifstream in("/tmp/output");  

     MyClass mm(3);  
     cout<< mm.i << endl;  
     mm.write(&out);  

     MyClass mm2(2);  
     cout<< mm2.i << endl;  
     mm2.read(&in);  
     cout<< mm2.i << endl;  

     return 0;  
}

但是运行的输出显示mm.i的值二进制文件未正确读取并分配给mm2.i

However the running output show that the value of mm.i supposedly written to the binary file is not read and assigned to mm2.i correctly

$ ./main   
3  
2  
2  

这样做有什么问题?

当我通常在二进制文件中写入或读取类的对象时,我应该注意什么?

What shall I be aware of when generally writing or reading an object of a class into or from a binary file?

推荐答案

正在缓冲数据,因此当您阅读它时,它实际上没有到达该文件。由于您使用两个不同的对象来引用in / out文件,因此操作系统并不知道它们是如何相关的。

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.

您需要刷新文件:

mm.write(&out);
out.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); 
    }

    ...
}

这篇关于向二进制文件中写入和读取类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆