Writing and reading (fwrite – fread) structures with pointers

Of course, that will not work as for strings it will copy the size of pointer, (usually 4 bytes). I see 3 options here:

  1. Serializing data, binary file (http://en.wikipedia.org/wiki/Serialization).
  2. Creating a format to store data in a text file.
  3. Use markup language like XML/JSON etc.

In any case you would need to go through every field of the structure in order to write it to data file. As for reading, in first 2 cases you would have to do reading exactly in the order you wrote the data, in third case you would be able to read fields independently in any order.

In case you choose first method, for every string (char *) field write also zero-termination byte so that you always know where it ends when reading it back.

Leave a Comment