-
题目描述:
-
从学生成绩文件A.txt,按照成绩递减顺序排序,并把排序后的成绩及对应名字写入文件B.txt中
-
样例输入:
-
A.txt中数据格式(只有一行):
张三 98,李四 89,王五 90
-
代码:
-
# include <stdio.h> # include <stdlib.h> typedef struct student { char name[10]; int grade; }student; student stu[20]; int cmp (const void*a,const void *b) { student* x=(student*)a; student* y=(student*)b; return x->grade-y->grade; } int main () { FILE* in; FILE* out; int i=0,j; char t[10]; if ((in=fopen("A.txt","rb"))==NULL) { printf ("cannot open file A\n"); exit(0); } if ((out=fopen("B.txt","wb"))==NULL) { printf ("cannot open file B\n"); exit(0); } while (fscanf(in,"%s %d",stu[i].name,&stu[i].grade)!=EOF) { i++; if (fscanf(in,"%c",t)==EOF) break; fscanf(in,"%c",t); } fclose (in); qsort(stu,i,sizeof(student),cmp); for (j=0;j<i;j++) { fprintf(out,"%s %d",stu[j].name,stu[j].grade); if (j!=i-1) fprintf(out,"%s",","); } fclose (out); printf ("ok!\n"); return 0; }