学生记录排序:对保存在文件中的记录按学号排序,排序后的记录仍写回原来的文件
时间: 2024-03-08 18:49:54 浏览: 22
对学生记录按照学号排序,可以使用冒泡排序或快速排序等排序算法。下面是一个使用冒泡排序的示例代码:
```
typedef struct {
int id; // 学号
char name[20]; // 姓名
int score; // 成绩
} Student;
void sort() {
FILE *fp;
Student students[100];
int i, j, n;
// 读取记录
if ((fp = fopen("students.dat", "rb+")) == NULL) {
printf("Can't open file!\n");
return;
}
n = fread(students, sizeof(Student), 100, fp);
fclose(fp);
// 冒泡排序
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (students[j].id > students[j+1].id) {
// 交换记录
Student temp = students[j];
students[j] = students[j+1];
students[j+1] = temp;
}
}
}
// 写回文件
if ((fp = fopen("students.dat", "wb+")) == NULL) {
printf("Can't open file!\n");
return;
}
fwrite(students, sizeof(Student), n, fp);
fclose(fp);
}
```
该函数先读取文件中的所有记录,然后使用冒泡排序对记录按照学号进行排序,最后将排序后的记录写回文件中。注意,在排序过程中,需要使用一个临时变量来交换记录。同时,需要考虑文件读写的错误处理。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)