保研练习题(1)

从键盘输入 4 个学生的数据( 包括姓名、年龄和成绩),并存放在文件 sf1 上。

从该文件读出这些数据,按成绩从高到底排序,并输出所有数据。

 1 #include <stdio.h>
 2 
 3 // 定义学生信息结构
 4 struct stu
 5 {
 6     char name[100];
 7     int age;
 8     int res;
 9 };
10 
11 int main()
12 {
13     struct stu stu[4];
14     struct stu fstu[4];
15     struct stu tmp;
16     FILE *fwrt,*fred;
17     int i,j;
18     printf("Please input information of student.\n");
19     fwrt= fopen("sf1.txt","wb+");
20     for (i=0; i<4; i++){
21         scanf("%s",stu[i].name);
22         scanf("%d",&stu[i].age);
23         scanf("%d",&stu[i].res);
24         fprintf(fwrt,"%s %d %d ",stu[i].name,stu[i].age,stu[i].res);
25     }
26     fclose(fwrt);    // 本句关闭很重要,因为以上以“二进制写”方式打开,以下却以“读”方式打开同一文件
27     fred = fopen("sf1.txt","r");
28     if (fred == NULL){
29         return 0;
30     }
31     for (i=0; i<4; i++){
32         fscanf(fred,"%s %d %d ",fstu[i].name,&fstu[i].age,&fstu[i].res);
33     }
34     fclose(fred);
35     // 冒泡排序
36     for (i=0; i<3; i++){
37         for (j=0; j<3-i; j++){
38             if (fstu[j].res < fstu[j+1].res){
39                 tmp = fstu[j];
40                 fstu[j] = fstu[j+1];
41                 fstu[j+1] = tmp;
42             }
43         }
44     } 
45     for (i=0; i<4; i++){    // 输出结果
46         printf("%s %d %d\n",fstu[i].name,fstu[i].age,fstu[i].res);
47     }
48     return 0;
49 }

posted on 2013-09-14 22:18  RAUL_AC  阅读(303)  评论(0编辑  收藏  举报

导航