写作和阅读(FWRITE - FREAD)结构的指针 [英] Writing and reading (fwrite - fread) structures with pointers

查看:152
本文介绍了写作和阅读(FWRITE - FREAD)结构的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作邮箱项目,我有这两种结构:

结构mmbox_mail

 结构mmbox_mail {
  字符*发件人,收件人*;
  字符* OBJ,*日期;
  字符标志;
  为size_t的大小;
};

mail_t

  typedef结构{
  结构体mmbox_mail信息;
  void *的机构;
  void *的下一个;
} mail_t;

我不能修改结构领域,因为我需要可变数据(为此我用的char *代替的char [])。

每个mail_t结构邮件。我需要一个用户的每一个邮件保存在一个文件中,这可能是二进制或文本文件(但我认为这是一个二进制文件更好,因为我有无效* 身体是难以以纯文本格式保存。

我试图做到这一点,但现在看来似乎不工作:

 而(mailtmp!= NULL){
  FWRITE(mailtmp,sizeof的(mail_t),1,FP);  / *的下一个邮件* /
  mailtmp = mailtmp->接下来,
}


 而(mailtmp!= NULL){/ *我有邮件列表,我使用的是mailtmp指针保存每个邮件* /


你能帮助我吗?我试着到处寻找,但我从来没有发现有人问救两个结构,一是里面的另外一个。


解决方案

当然,这将不会作为字符串将复制指针的大小,(通常为4个字节)的工作。我在这里看到3个选项:


  1. 序列化数据,二进制文件(http://en.wikipedia.org/wiki/Serialization)。

  2. 创建将数据存储在一个文本文件的格式。

  3. 使用标记语言如XML / JSON等。

在任何情况下,你需要通过结构的各个领域,以便将其写入到数据文件。至于阅读,在最初2情况下,你必须做在你写的数据,在第三种情况下的顺序,你将能够以任意顺序独立阅读领域正是阅读。

如果你选择第一种方法,对于每一个字符串(字符*)字段的写入也为零终止字节,这样你总是知道它看完回来时结束。

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.

解决方案

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.

这篇关于写作和阅读(FWRITE - FREAD)结构的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆