Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write and read object of class into and from binary file

Tags:

c++

file

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

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?

like image 509
Tim Avatar asked Jan 12 '10 05:01

Tim


1 Answers

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

    ...
}
like image 136
R Samuel Klatchko Avatar answered Oct 03 '22 12:10

R Samuel Klatchko