Writing a structure to a file which contains pointers to dynamically allocated memory would not work. You'd have to set those members to something else when you read in the file, since the pointers would be invalid next time you read the data into memory (unless the same instance of the program was still running), which would defeat the purpose.
You could, however, do something like this:
Code:
struct string_t {
size_t len;
char *data;
};
Then you'd write that structure to the file followed by the data in data. When reading that structure in, you'd look at len and read that many more bytes into data.
Something like this:
Code:
struct string_t str = {3, "abc"};
fwrite(&str, sizeof(str), 1, fp);
fputs(str.data, fp);
/* ... */
fread(&str, sizeof(str), 1, fp);
read_bytes(str.len, &str.data);
where read_bytes() would read str.len bytes into str.data, which would be dynamically allocated. Maybe like this, without error checking.
Code:
void read_bytes(size_t len, char **data) {
size_t x;
*data = malloc(len + 1);
for(x = 0; x < len; x ++) {
data[x] = fgetc(fp);
}
data[x] = 0;
}