Need help with serialization

I am trying to write a program to serialize a linked list to a file without using any libraries. My problem is how to add or remove nodes in a serialized structure, since I don't have the following pointer? Also, how can I avoid fragmentation?

+4
source share
1 answer

If your linked list has no loops, then the fact that this is a β€œlinked list” is a memory part, not a serialization detail. Just write the node values ​​to the file and create next pointers when deserializing.

However, if your linked list has loops, then you will need something smarter. You will need to store the next pointers as the file offset to the node (or something similar) to encode the "link".

For each node in a linked list, save two words. The first is the data, the second is the offset of the next node. Here is an illustration of a circular list:

  +-> 1234 -> 5678 -> 2398 -+ | | +-------------------------+ 0 : 4bytes: 1234 : int data <------------+ 4 : 4bytes: 8 : offset of next node -+ | | | 8 : 4bytes: 5678 : int data <----------+ | 12 : 4bytes: 16 : offset of next node -+ | | | 16 : 4bytes: 2398 : int data <----------+ | 20 : 4bytes: 0 : offset of next node ---+ 
+5
source

Source: https://habr.com/ru/post/1313462/


All Articles