I really don't understand. There are many solutions existing on the internet. Search for "c++ object serialization".
Binary or Textual representation in file.
Before you start writing an object to a file, you need to decide whether you are writing binary or textual representations.
A binary representation mirrors the bits and bytes of the platform's representation. Numbers and other structures may not be easily readable when viewed by a text editor. This is usually the most efficient, but least portable solution. Pointers don't do well, neither may multi-byte integers (research "Endianess" or "little endian"). Variable length fields require more structure in the binary field (such as a length field or sentinel value).
A textual representation is the human readable form. The textual form is more portable and easier to read by humans. This form is slower to read and write (due to the translations to and from textual format). Also, pointer values do not port with this format (unless you use numeric link values).
Writing textual representation to file.
There are a plethora of examples on the internet. I will summarize and say that this functionality usually involves overloading operator <<
and operator >>
. Which means adding functionality to your classes and structures (or you could make a free standing function).
Serialization Libraries
Many people use these. I cannot recommend or not recommend these because I haven't used them. In summary, these libraries simplify the reading and writing of objects from and to a file.
Writing Binary Format
Again, this requires adding functionality to your classes and structures (or making free standing functions). I like to augment the typical case of using the std::istream::read
and std::ostream::write
methods.
I use a technique of:
1. Asking each object for the size that the object would occupy in a buffer, and summing the values.
1.1. This is recursive, each object would ask each member for its size.
2. Allocating a buffer of uint8_t
for the size.
3. Pass a pointer to the buffer to each object and tell each object to write its contents at the location pointed to by the buffer pointer (the objects will increment the pointer accordingly).
4. Write the buffer as one big block, using binary translation, to the file.
5. The reading is similar, different order.