Hi, 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 myc
{
public:
int i;
myc(int n) {i = n; }
myc(){}
void read(ifstream *in){in->read((char *) this, sizeof(myc));}
void write(ofstream *out){out->write((char *) this, sizeof(myc));}
};
int main(int argc, char * argv[])
{
ofstream out("/tmp/output");
ifstream in("/tmp/output");
myc mm(3);
cout<< mm.i << endl;
mm.write(&out);
myc mm2(2);
cout<< mm2.i << endl;
mm2.read(&in);
cout<< mm2.i << endl;
return 0;
}
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
So what's wrong with it?
What shall I be aware of when generally writing or reading an object of a class into or from a binary file?
Thanks!