从海量数据中寻找某一学生,并更改其成绩(运用二分查找法,文件定位)

    xiaoxiao2022-06-27  172

    #include<stdio.h> #include<stdlib.h> #include<string.h> struct student { int num; char name[20]; int score; }t; int main() { FILE *fp; fp=fopen("student.dat","rb+"); if(!fp) exit(0); char name[20]; puts("请输入查找的学生姓名:"); gets(name); int low,n,high,mid; fseek(fp,0,2);//指针定位在文件末 n=ftell(fp)/sizeof(t); low=0; high=n-1; while(low<=high) { mid=(low+high)/2; fseek(fp,mid *sizeof(t),0); fread(&t,sizeof(t),1,fp); if(strcmp(t.name,name)==0) { puts("find"); t.score=88; fseek(fp,-sizeof(t),1);//回跳 fwrite(&t,sizeof(t),1,fp); break; } else if(strcmp(t.name,name)>0) { high= mid-1; } else { low=mid+1; } } if(low>high) puts("no find"); rewind(fp);//回到文件头 while(fread(&t,sizeof(t),1,fp))//检验是否操作成功 { printf("%d %s %d\n",t.num ,t.name ,t.score ); } fclose(fp); return 0; }

     


    最新回复(0)