gpt4 book ai didi

c - 将结构数组写入 C 中的二进制文件

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

我有一个结构数组,我想写入一个二进制文件。我有一个 write.c 程序和一个 read.c 程序。 write.c 程序似乎工作正常,但是当我运行 read.c 程序时,出现段错误。我是 C 的新手,所以如果有人可以检查我的代码是否有任何明显的错误,那就太好了。我保证不会太长:)

写.c:

#include <stdlib.h>
#include <stdio.h>

struct Person
{
char f_name[256];
char l_name[256];
int age;
};

int main(int argc, char* argv[])
{
struct Person* people;
int people_count;

printf("How many people would you like to create: ");
scanf("%i", &people_count);
people = malloc(sizeof(struct Person) * people_count);

int n;
for (n = 0; n < people_count; n++)
{
printf("Person %i's First Name: ", n);
scanf("%s", people[n].f_name);

printf("Person %i's Last Name: ", n);
scanf("%s", people[n].l_name);

printf("Person %i's Age: ", n);
scanf("%i", &people[n].age);
}

FILE* data;
if ( (data = fopen("data.bin", "wb")) == NULL )
{
printf("Error opening file\n");
return 1;
}

fwrite(people, sizeof(struct Person) * people_count, 1, data);
fclose(data);

return 0;
}

读.c:

#include <stdlib.h>
#include <stdio.h>

struct Person
{
char f_name[256];
char l_name[256];
int age;
};

int main(int argc, char* argv[])
{
FILE* data;
if ((data = fopen("data.bin", "rb")) == NULL)
{
printf("Error opening file\n");
return 1;
}

struct Person* people;

fread(people, sizeof(struct Person) * 1/* Just read one person */, 1, data);
printf("%s\n", people[0].f_name);

fclose(data);

return 0;
}

感谢您的帮助!

最佳答案

struct Person* people;

这只分配了一个指向结构的指针,但您没有为实际结构内容分配任何空间。要么像您的写入程序一样使用 malloc,要么尝试类似的方法:

struct Person people;
fread(&people, sizeof(people), 1, data);

关于c - 将结构数组写入 C 中的二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4368677/

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