我有一個我想寫入二進制文件的結構數組。我有一個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