從海量數據中尋找某一學生,並更改其成績(運用二分查找法,文件定位)

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章