我尝试在C++中向二进制文件写入和读取类的对象.我不想单独编写数据成员,而是一次编写整个对象.举个简单的例子:
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;
}
Run Code Online (Sandbox Code Playgroud)
但运行输出显示,无法读取写入二进制文件的mm.i值,并正确分配给mm2.i.
$ ./main
3
2
2
Run Code Online (Sandbox Code Playgroud)
那有什么不对呢?
通常在二进制文件中写入或读取类的对象时,我应该注意什么?
R S*_*hko 11
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()
Run Code Online (Sandbox Code Playgroud)
or close the file (which does an implicit flush):
mm.write(&out);
out.close()
Run Code Online (Sandbox Code Playgroud)
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);
}
...
}
Run Code Online (Sandbox Code Playgroud)
Dumping raw data is a terrible idea, from multiple angles. This will break even worse once you add pointer data.
One suggestion would be to use Boost.Serialization which allows for far more robust data dumping.
Your main problem is the file does not contain the contents yet due to fstream buffering. Close or flush the file.