C程序设计 (第四版) 谭浩强 习题10.6
习题10.6 将第5题"stud"文件中的学生数据,按平均分进行排序处理,将已排序的学生数据存入一个新文件"stu_sort"中。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法:使用指针,函数的模块化设计,动态分配内存
说明:这里准备读取的文件名stud.dat,文件已经存在于该项目目录下,准备写入的文件stu_sort.dat通过程序建立。
#include <stdio.h>
#include <stdlib.h>#define N 5typedef struct{int num;char name[20];float score[3];float aver;
}Student;void initialStu(Student **stu, int n, char **name){*stu = (Student*)malloc(n * sizeof(Student));*name = (char*)malloc(80 * sizeof(char));
}
void sortByAverStu(Student *stu, int n){Student temp;for(int i = 0; i < n; i++){for(int j = i + 1; j < n; j++){if(stu[i].aver < stu[j].aver){temp = stu[i];stu[i] = stu[j];stu[j] = temp;}}}
}void inputFileName(FILE **file, char *name){printf("Enter File Name: ");scanf("%s", name);*file = fopen(name, "rb");if(*file == NULL){perror("Cannot open this file");system("pause");exit(0);}
}void readFileAndSort(FILE **file, char *name, Student *stu, int n){for(int i = 0; i < n; i++){fread(&stu[i], sizeof(Student), 1, *file);}sortByAverStu(stu, n);
}void inputFile(FILE **file, char *name, Student *stu, int n){printf("Enter New File Name: ");scanf("%s", name);*file = fopen(name, "wb");if(*file == NULL){perror("File Error");system("pause");exit(0);}for(int i = 0; i < n; i++){if(fwrite(&stu[i], sizeof(Student), 1, *file) != 1){perror("File write error");system("pause");exit(0);}}fclose(*file);
}void outputFile(FILE **file, char *name, Student *stu, int n){*file = fopen(name, "rb");if(*file == NULL){perror("Cannot open this file");system("pause");exit(0);}printf("Read File Info:\n");for(int i = 0; i < n; i++){fread(&stu[i], sizeof(Student), 1, *file);printf("Number: %-3d Name: %-10s Score: ", stu[i].num, stu[i].name);for(int j = 0; j < 3; j++){printf("%-3.2f ", stu[i].score[j]);}printf("Average: %-3.2f\n", stu[i].aver);}printf("\n");fclose(*file);
}void freeStu(Student **stu, char **name){free(*stu);free(*name);
}int main(){FILE *file1 = NULL;FILE *file2 = NULL;Student *stu = NULL;char *name = NULL;initialStu(&stu, N, &name);inputFileName(&file1, name);outputFile(&file1, name, stu, N);readFileAndSort(&file1, name, stu, N);inputFile(&file2, name, stu, N);outputFile(&file2, name, stu, N);freeStu(&stu, &name);system("pause");return 0;
}
运行结果如下:
