Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

c - Writing and reading (fwrite - fread) structures with pointers

I'm working on a mailbox project, and I have these two structures:

struct mmbox_mail

struct mmbox_mail {
  char *sender, *recipient; 
  char *obj, *date;
  char flags; 
  size_t size; 
};

and

mail_t

typedef struct{
  struct mmbox_mail info;
  void *body;
  void *next;
} mail_t;

I cannot modify the structures' fields, because I need variable data (for this purpose I used char* instead of char[]).

Each mail_t structure is a mail. I need to save every mail of a user in a file, that could be binary or text file (but I think it's better with a binary file, because I have the void* body that is difficult to save in plain text.

I tried to do this, but it seems like it doesn't work:

while(mailtmp != NULL){
  fwrite(mailtmp, sizeof(mail_t), 1, fp);

  /* next mail */
  mailtmp=mailtmp->next;
}
while(mailtmp != NULL){  /* i have a list of mails and i use a mailtmp pointer to save each mail */

Could you help me? I tried to search everywhere but I never found someone that ask to save two structures, one inside one other.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...