我有一个我想写入二进制文件的结构数组。我有一个write.c程序和一个read.c程序。 write.c程序似乎工作正常,但是当我运行read.c程序时,出现了分段错误。我是C新手,所以如果有人能够查看我的代码,发现任何明显的错误,那将是非常棒的。我保证这不是太长:)将结构数组写入C中的二进制文件
为write.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;
}
read.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;
}
感谢您的帮助!
这个问题每天会被询问多少次?应该有一个'C'的常见问题解答,让我们指出答案,而不是花时间写下所有这些停顿的时间...... – KevinDTimm 2010-12-06 16:57:51