1 #include "stdafx.h" 2 #include <stdlib.h> 3 #include <stdio.h> 4 #define N 30 5 typedef struct date 6 { 7 int year; 8 int month; 9 int day; 10 }DATE; 11 typedef struct student 12 { 13 long studentID; 14 char studentName[10]; 15 char studentsex; 16 DATE birthday; 17 int score[4]; 18 float aver; 19 }STUDENT; 20 int SearchNuminFile(char fileName[],long key); 21 int main() 22 { 23 int n; 24 long key; 25 printf_s("Input the searching ID:"); 26 scanf_s("%d",&key,sizeof(key)); 27 n = SearchNuminFile("student.txt",key); 28 if(n != -1) 29 printf_s("Record number is %d. ",n); 30 else 31 printf_s("Not found. "); 32 return 0; 33 } 34 int SearchNuminFile(char fileName[],long key) 35 { 36 FILE *fp; 37 STUDENT stu[N]; 38 int i,j; 39 if(fopen_s(&fp,fileName,"r") == NULL) 40 { 41 printf_s("Failure to open %s! ",fileName); 42 exit(0); 43 } 44 system("pause"); 45 for(i = 0;!feof(fp);i++) 46 { 47 fread(&stu[i],sizeof(STUDENT),1,fp); 48 if(key == stu[i].studentID) 49 { 50 printf_s("%10ld%8s%3c%6d/%02d/%02d",stu[i].studentID, 51 stu[i].studentName,stu[i].studentsex,stu[i].birthday .year, 52 stu[i].birthday.month,stu[i].birthday.day); 53 for(j = 0;j < 4;j++) 54 { 55 printf("%4d",stu[i].score[j]); 56 } 57 printf_s("%6.1f ",stu[i].aver); 58 fclose(fp); 59 return i+1; 60 } 61 } 62 fclose(fp); 63 system("pause"); 64 return -1 ; 65 }