バイナリファイルに書きたい構造体の配列があります。私は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;
}
ありがとう!
この質問は1日に何回尋ねられますか?時間の経過とともにこのダウンタイムを書いた時間を費やすのではなく、答えを指すことができる「C」FAQがあるはずです...... – KevinDTimm