c - 在 C 中将某些变量保存到二进制文件时出错

标签 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== 

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

最佳答案

您需要了解“序列化”的概念。这就是将数据存储在文件中(或在线路上)并将其读回。您不能只是将内容转储到文件中(除了极少数简单的情况)。

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

关于c - 在 C 中将某些变量保存到二进制文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39213061/

相关文章:

c - 为什么选项 -m32 在我的 Linux 操作系统上不起作用?

c - ret指令后面的lea指令是什么意思?

无法从 C 中的文本文件中读取所有名称

c - 在标准 C 中声明固定大小的整数 typedef

在 C 中将 Char 数组转换为 Long

c - 如何使用 pthread_cond_wait() 和 pthread_cond_signal()?

c - 中断阻塞读

c++ - 可变参数

c - 变量取一定值时的断点

java - 如何动态执行给变量的内容