tags:

views:

108

answers:

3

Hi all,

Assume I have a class

class A
{
 char *attr1,*attr2;
public:
 . . .
};

How to save the object of this class to file in a binary format and read it back?

Thanks.

+1  A: 

Read about serialization. For example the Boost serialization library. They have a nice definition:

Here, we use the term "serialization" to mean the reversible deconstruction of an arbitrary set of C++ data structures to a sequence of bytes. Such a system can be used to reconstitute an equivalent structure in another program context. Depending on the context, this might used implement object persistence, remote parameter passing or other facility. In this system we use the term "archive" to refer to a specific rendering of this stream of bytes. This could be a file of binary data, text data, XML, or some other created by the user of this library.

That said, such a solution is the 5-kg hammer that solves most serialization problems. It may be the case that you need something far simpler. For example, if you object only consists of a few char* attributes you can save it in a simpler way. A general solution, however, would allow you flexibility in case your object gets more complex in the future.

Eli Bendersky
I dont have any problem in saving the objects. But reading back from a file is bit tricky as I guess :) I am using:"ofstream outbal("fileName", ios::out | ios::binary);""outbal.write((char *) "But not getting how can i read it back from file :(
Manjunath
@Manjunath You are writing out the pointers to the strings, but not the strings they are pointing to.
Eddy Pronk
@Manjunath: the serialization library gives you tools to both write and read back the data, of course!
Eli Bendersky
A: 

You might want to try xml


Instead of Binary, You might want to try xml.

The (field=value) format is very easily parsed back too.

http://cppxmlobj.sourceforge.net/

Also checkout this Qustion:

http://stackoverflow.com/questions/974815/how-to-save-c-object-into-a-xml-file-and-restore-back

GoodLUCK!!

CVS-2600Hertz
Signatures are discouraged, see e.g. here: http://meta.stackoverflow.com/questions/5029/are-taglines-signatures-disallowed
Georg Fritzsche
@gf Totally discouraged?? oh.ok.... :( ROGER that GF!! ;-)
CVS-2600Hertz
+2  A: 

For efficient, fast and extensible binary serialization format, take a look at Google protocol buffers.

Employed Russian