Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

You have to write your own serialization function or not to use pointers. It actually depends on your tasks. I prefer using fixed length arrays everywhere it's possible.

If your task is more complex look at libraries like tpl to serialize your data structures.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top