gpt4 book ai didi

c - 在 C 中写入指向文件的指针

转载 作者:太空狗 更新时间:2023-10-29 17:15:17 26 4
gpt4 key购买 nike

我有一个结构:

typedef struct student {
char *name;
char *surname;
int age;
} Student;

我需要将结构写入二进制文件。
这是我的尝试:

Student *s = malloc(sizeof(*s));

我用数据填充我的结构,然后我将结构写入文件:

fwrite(s, sizeof(*s), 1, fp);

在我的文件中,名字和姓氏不存在。相反,它们具有各自的 char * 指针地址。
如何将 char * 写入文件而不是指针地址?

最佳答案

您需要取消引用您的指针并编写结构的各个部分。 (你不应该直接 fwrite 一个结构,而是编码它的部分然后写那些:

Student *s = malloc(sizeof(*s));
s->name = "Jon";
s->surname = "Skeet";
s->age = 34;

// ....

fwrite(s->name, sizeof(char), strlen(s->name) + 1, fp);
fwrite(s->surname, sizeof(char), strlen(s->surname) + 1, fp);

//This one is a bit dangerous, but you get the idea.
fwrite(&(s->age), sizeof(s->age), 1, fp);

关于c - 在 C 中写入指向文件的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2763438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com