我用C编写了一个小程序,它在二进制文件中创建了一个学生列表。我调用函数fsearch()
(如下)来搜索指定的学生并更改他的数据,但数据似乎没有被修改。
// the file is opened in mode "wb+"
int fsearch(FILE *f)
{
student s;
float matsearch;
printf("enter the matricule you want to find ");
scanf("%f",&matsearch);
rewind(f); // starting the search from the beginning
while(fread(&s,sizeof(student),1,f)==1 && s.mat!=matsearch);
if(s.mat==matsearch)
{
printf("we found what searched for\n");
printf("name: %s\n",s.fname);
printf("last name: %s\n",s.lname);
printf("matricule: %.f\n",s.mat);
fseek(f,-sizeof(student),SEEK_CUR);
student a;
scanf("%s",&(a.fname));
scanf("%s",&(a.lname));
scanf("%d",&(a.mat));
if(fwrite(&a,sizeof(student),1,f)==1)
{
printf("successfully wrote"); // this message does get printed
}
return(1); // successfully found
}
printf("we didn't find what you searched for\n");
return(0);
}
最佳答案
除了bluesawsdust发布的代码外,我还发现了代码中的其他一些错误:// the file is opened in mode "wb+"
:这意味着您的文件在打开时被销毁(请参见here)。您可能需要使用"rb+"
因为您没有初始化student s
结构(而且由于我的上一点,它从未写入任何记录)s.mat
包含一个随机值scanf("%d",&(a.mat));
:对于printf
,您应该将格式字符串更改为"%f"
(但实际上您应该使用字符串类型,比较float
s和==
并不是很好的做法,因为使用了roundings)
关于c - 为什么fwrite不覆盖wb +中的数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29977656/