Search code examples
cfwritefread

Best way to fwrite/fread a dynamic linked list in C


I have this structure:

struct data
{
    int id;
    char *title;
    char *description;
    int year;
};

Now I have to save the list in a file, using fwrite, and then read it with fread.

What is the best way? I can't do something like

fwrite(info, sizeof(struct data), 1, ptr_file);

Because the structure has two pointers. And if I write field by field and use strlen to write the strings, how could I know the size of each string while reading?

Thanks.


Solution

  • You can't write structures with pointers to a file, as that will write the pointer and not what they point to to the file. This means that when you later try to read the structure, the pointers will point to "random" memory.

    You might want to read about serialization.

    A simple scheme is to write the id and year members separately, then the length (as a fixed-size value) of the first string, followed by the string, then the length of the second string and the actual string.

    Another, even simpler, method is to have fixed-size arrays instead of pointer for the strings. This have the drawback that if you don't use all the space allocated for the arrays then you waste some memory. An even worse drawback is that you can't have strings larger than the arrays.