我用 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);
}
最佳答案
除了bluesawdust发的那个,我还发现了一些其他的代码错误:
//文件以“wb+”模式打开
:这意味着您的文件在打开时被破坏(参见 here )。您可能想使用"rb+"
因为您没有初始化您的
student s
结构(并且由于我之前的观点,没有记录被写入其中)s.mat
包含一个随机值scanf("%d",&(a.mat));
:对于printf
,需要将格式字符串改为"%f"
(但实际上你应该使用字符串类型,将float
与==
进行比较不是好的做法,因为四舍五入)
关于c - 为什么 fwrite 不覆盖我在 wb+ 中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977656/