将一些变量保存到C中的二进制文件时出错

时间:2016-08-29 18:43:12

标签: c

我正在尝试将这个医院管理计划用于学校工作,我遇到了这个错误,并且真的不知道如何解决它。我很感激有人来指导我。 预先感谢。

我有这个链表:

struct marcacao
{
  char nome[50];
  int idade;
  struct marcacao *next;
};

使用此功能

创建
void make_apt(struct marcacao **head_apt)

struct marcacao tmp;
...
  while( *head_apt )
    head_apt = &(*head_apt)->next;
...
printf("Nome do Paciente > ");
scanf(" %[^\n]", tmp.nome);
printf("Idade do Paciente > ");
scanf("%d", &tmp.idade);

tmp.next = NULL;

if ( !(*head_apt = malloc( sizeof (**head_apt) ) ) )
{
  printf("Erro a alocar novo no ");
  return;
}
**head_apt = tmp;
...

我必须将信息保存在二进制文件中,因此可以在下次执行时恢复。

void sv_apt(struct marcacao *head_apt)

FILE *f = fopen(APT_FILE, "wb");
...

while(head_apt)
{
  fwrite(head_apt->nome, sizeof(head_apt->nome), 1, f);
  fwrite(&head_apt->idade, sizeof(head_apt->idade), 1, f);
  head_apt = head_apt->next;
}

但是valgrind正在这样做:

==18255== Syscall param write(buf) points to uninitialised byte(s)
==18255==    at 0x4F22710: __write_nocancel (syscall-template.S:81)
==18255==    by 0x4EAFF02: _IO_file_write@@GLIBC_2.2.5 (fileops.c:1261)
==18255==    by 0x4EB13DB: new_do_write (fileops.c:538)
==18255==    by 0x4EB13DB: _IO_do_write@@GLIBC_2.2.5 (fileops.c:511)
==18255==    by 0x4EB0C5F: _IO_file_close_it@@GLIBC_2.2.5 (fileops.c:165)
==18255==    by 0x4EA4A4F: fclose@@GLIBC_2.2.5 (iofclose.c:59)
==18255==    by 0x401CD3: sv_apt (apt.c:125)
==18255==    by 0x401A11: make_appointment (apt.c:43)
==18255==    by 0x400B20: main (main.c:31)
==18255==  Address 0x402700c is not stack'd, malloc'd or (recently) free'd
==18255== 

使用十六进制编辑器,我可以看到信息保存得不好。

1 个答案:

答案 0 :(得分:1)

你需要理解'序列化'的概念。那就是将数据存储在文件中(或在线上)并将其读回。你不能只将东西转储到一个文件中(除了罕见的简单案例)。

您需要选择序列化格式。我建议使用基于ASCII的东西,因为它易于编辑和调试。使用json,xml或yaml。