To serialize objects, you need to adhere to the concept that an object writes its members to a stream and reads elements from the stream. In addition, member objects must be written to the stream (as well as read).
I implemented a scheme using three member functions and a buffer:
void load_from_buffer(uint8_t * & buffer_pointer); void store_to_buffer(uint8_t * & buffer_pointer) const; unsigned int size_on_stream() const;
size_on_stream will be called first to determine the size of the buffer for the object (or how much space it takes in the buffer).
The load_from_buffer function loads the elements of an object from the buffer using the specified pointer. The function also increments the pointer accordingly.
The store_to_buffer function stores the elements of objects in the buffer using the specified pointer. The function also increments the pointer accordingly.
This can be applied to POD types using templates and specialized templates.
These features also allow you to pack output into a buffer and load from a packed format.
The reason for the I / O for the buffer is to use more efficient block-stream methods, such as write and read .
Edit 1: Writing node to stream
The problem with writing or serializing a node (such a linked list or node tree) is that pointers are not translated to the file. There is no guarantee that the OS will place your program in the same memory location or give you the same memory area each time.
You have two options: 1) Save data only. 2) Convert pointers to file offsets. Option 2) is very complicated, as it may require re-setting the file pointer, since file offsets may not be known in advance.
Also note variable length entries such as strings. You cannot directly write a string object to a file. If you do not use a fixed line width, the line size will change. You will need to either prefix a string with a string length (preferred) or use some kind of trailing character, such as '\ 0'. The length of the string is preferable at first because you do not need to look for the end of the string; you can use a block read for reading in text.