1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 struct student //定義結構體 5 { 6 char name[7]; //姓名 7 int number; //號碼 8 }student,student1; 9 void menu() //顯示欄 10 { 11 printf("***********************\n"); 12 printf("1 input record\n"); 13 printf("2 search record\n"); 14 printf("0 quit system\n"); 15 } 16 void save() //輸入函數 17 { 18 FILE *fp; 19 system("cls"); //清屏 20 fp=fopen("filename","a+"); 21 if(fp==NULL) 22 { 23 printf("open file error"); 24 exit(1); 25 } 26 while(1) 27 { 28 scanf("%s%d",student.name,&student.number); //輸入姓名及號碼 29 fwrite(&student,sizeof(struct student),1,fp); 30 printf("continue?(y/n)"); //是否繼續 31 getchar(); 32 if(getchar()=='n') break; 33 } 34 fclose(fp); 35 exit(0); 36 } 37 void search()//查找函數 38 { 39 40 FILE *fp; 41 char name[7]; 42 system("cls");//清屏 43 if((fp=fopen("filename","r"))==NULL) 44 { 45 printf("open the file error"); 46 exit(1); 47 } 48 printf("please int your name\n"); 49 scanf("%s",name); 50 while(fread(&student1,sizeof(struct student),1,fp)==0)//查找 51 { 52 if(strcmp(student1.name,name)==0) 53 { 54 printf("%s %d",student1.name,student1.number);//顯示所查找的姓名以及號碼 55 break; 56 } 57 } 58 if(feof(fp))//檢測文件指針指向文件是否結束 59 { 60 printf("search fail");//若結束則輸出查找失敗 61 exit(0); 62 } 63 } 64 int main()//主函數 65 { 66 int select; 67 menu();//顯示主菜單 68 printf("\nPlease enter your select\n"); 69 scanf("%d",&select); 70 while(select) 71 { 72 switch(select) 73 { 74 case 1:save();break; 75 case 2:search();break; 76 case 0:exit(1); 77 } 78 } 79 }