tags:

views:

181

answers:

4

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!

+1  A: 

My C++ is pretty rust and highly under-tested, but you may want to take a look at Serialization and Unserialization. FAQ

Amit
+4  A: 

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); 
    }

    ...
}
R Samuel Klatchko
Thanks! Is it possible to define a single object for both file writing and reading in C++? I remember it is possible in C.
Tim
@Tim. YEs you can have a file-stream opened for reading and writing.
Martin York
+5  A: 

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.

Yann Ramin
+1  A: 
Hostile Fork