C字符数组到二进制文件
它不起作用了。当我想在3中添加int时。行我得到了“分割错误”,但我不知道为什么 请检查一下,好吗C字符数组到二进制文件,c,segmentation-fault,binaryfiles,C,Segmentation Fault,Binaryfiles,它不起作用了。当我想在3中添加int时。行我得到了“分割错误”,但我不知道为什么 请检查一下,好吗 int felvetel() { FILE *ptr_myfile; struct stadion* my_record; my_record = malloc(sizeof(struct stadion) * 1); ptr_myfile=fopen("test.bin","wb"); if (!ptr_myfile) {
int felvetel()
{
FILE *ptr_myfile;
struct stadion* my_record;
my_record = malloc(sizeof(struct stadion) * 1);
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Nem lehet megnyitni a fajlt!");
return 1;
}
printf("Varos: ");
scanf("%s", my_record[0].varos);
printf("Csapat: ");
scanf("%s", my_record[0].csapat);
printf("Nezoszam: ");
scanf("%i", my_record[0].nezoszam);
printf("Koltseg: ");
scanf("%i", my_record[0].koltseg);
printf("Atadas eve: ");
scanf("%i", my_record[0].ev);
printf("Atadas honapa: ");
scanf("%i", my_record[0].honap);
printf("Atadas napja: ");
scanf("%i", my_record[0].nap);
fwrite(my_record, sizeof(struct stadion), 1, ptr_myfile);
fclose(ptr_myfile);
return 0;
}
我希望它工作正常,但我不能尝试,因为我的二进制文件中没有任何内容
为什么要将结构添加到二进制文件中两次?对于整数,
scanf
需要一个指向整数的指针,因此请传入例如和my_record.nezoszam
。什么是struct station
?poststruct station
@dvnrrs也scanf(%i“,&my_record[0].ev)代码>和scanf(“%i”、&my_记录[0]。honap)代码>和scanf(“%i”、&my_记录[0].nap)代码>。另外,亲爱的OP,显示struct station
的定义要比listazas
有用得多。是的,我们需要查看struct,以确保您有char
数组,而不是指针,但我认为@dvnrrs是值得的。
int listazas()
{
FILE *ptr_myfile;
struct stadion my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Nem lehet megnyitni a fajlt!");
return 1;
}
while (!(feof(ptr_myfile)))
{
fread(&my_record,sizeof(struct stadion),1,ptr_myfile);
printf("%s\t",my_record.varos);
printf("%s\t",my_record.csapat);
printf("%i\t",my_record.nezoszam);
printf("%i\t",my_record.koltseg);
printf("%i\t",my_record.ev);
printf("%i\t",my_record.honap);
printf("%i\t",my_record.nap);
}
fclose(ptr_myfile);
return 0;
}