1 #include <stdio.h> 2 #include <stdlib.h> 3 #define FILENAME "E:\\FUSHI\\students.txt" 4 5 struct student 6 { 7 int num;//学号 8 char name[20];//姓名 9 char rank; //成绩等级 10 int score;//成绩 11 }; 12 13 int main() 14 { 15 FILE *fp; 16 struct student stu; 17 fp=fopen(FILENAME,"wb"); 18 if(fp==NULL) 19 { 20 printf("不能打开文件:%s\n",FILENAME); 21 exit(1); 22 } 23 printf("请输入学生的学号、姓名、成绩:\n"); 24 scanf("%d",&stu.num); 25 while(stu.num!=0) 26 { 27 scanf("%s%d",stu.name,&stu.score); 28 switch(stu.score/10) 29 { 30 case 10: 31 case 9: 32 stu.rank='A';break; 33 case 8: 34 stu.rank='B';break; 35 case 7: 36 stu.rank='C';break; 37 case 6: 38 stu.rank='D';break; 39 default: 40 stu.rank='E';break; 41 } 42 fwrite(&stu,sizeof(struct student),1,fp); 43 scanf("%d",&stu.num); 44 } 45 fclose(fp); 46 47 fp=fopen(FILENAME,"rb"); 48 if(fp==NULL) 49 { 50 printf("不能打开文件:%s\n",FILENAME); 51 exit(1); 52 } 53 printf("学号 姓名 成绩 等级\n"); 54 fread(&stu,sizeof(struct student),1,fp); 55 while(!feof(fp)) 56 { 57 printf("%d %s %d %c\n",stu.num,stu.name,stu.score,stu.rank); 58 fread(&stu,sizeof(struct student),1,fp); 59 } 60 fclose(fp); 61 62 return 0; 63 }