is there any standard approach which I've missed at school to dump C structure with nested linked lists on disk in reasonable way? What I don't want to do is:
I've few ideas:
To image this I'll give some more details posting example code:
typedef struct{
int b;
List *next;
}List;
typedef struct{
float b;
List2 *next;
}List2;
typedef struct{
List *head;
List *tail;
} info;
typedef struct{
List2 *head;
List2 *tail;
} info2;
struct data
{
int a;
char t[10];
info first;
info second;
info2 third;
};
cheers P.
EDIT:
I've extended main structure, seems like previous one haven't indicate the problem fully. I'm aware that pointers on disk are useless. Ideas and pseudocode allowed.
Serialize the data in the order it's held in the linked list, record-style to a file. fwrite
is particularly good for this. Be sure to dereference pointers, and be aware of the role endianness plays in this.
Here's some vague pseudocode:
List *list_new();
List *list_add(List *, void *data);
List *list_next(List *);
while (node) {
fwrite(node->data, sizeof(node->data), 1, fp);
node = list_next(node);
}
Rough code for reading back into a live list:
List *node = list_new();
while (true) {
struct data *buf = malloc(sizeof(*buf));
if (1 != fread(buf, sizeof(*buf), 1, fp))
break;
list_add(node, buf);
}
If you begin to nest more advanced structures such as other linked lists, variable length strings etc., you'll need to provide types and lengths for each record, and a way to nest records within other records.
As an example, if your top level linked list had a data member that was another list, you'd be best to store that member as a nested record, complete with a length, and type field. Alternatively, you could define sentinel records, such as \0
for character strings (an obvious choice), and zeroed blocks for struct data.