建立两个磁盘文件f1.dat,f2.dat,编写程序实现以下工作:(1)从键盘输入学生姓名,学号,三科成绩,存放在一个磁盘文件中(3)从f1.dat中读入数据,将它们按从小到大的顺序存放到f2.dat(不保留原来的数据)*/
时间: 2024-05-13 17:17:44 浏览: 94
下面是一个基本的实现思路,供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100 // 最大学生数
#define MAX_NAME_LEN 20 // 最大姓名长度
// 定义学生结构体
typedef struct {
char name[MAX_NAME_LEN];
int id;
int score1;
int score2;
int score3;
} Student;
// 用于比较两个学生分数的函数
int cmp_scores(const void* a, const void* b) {
const Student* s1 = (const Student*)a;
const Student* s2 = (const Student*)b;
int total1 = s1->score1 + s1->score2 + s1->score3;
int total2 = s2->score1 + s2->score2 + s2->score3;
return total1 - total2;
}
int main() {
// 从键盘输入学生信息并写入磁盘文件
FILE* fp1 = fopen("f1.dat", "wb");
if (!fp1) {
printf("无法打开文件 f1.dat\n");
return 1;
}
int num_students;
printf("请输入学生数:");
scanf("%d", &num_students);
if (num_students <= 0 || num_students > MAX_STUDENTS) {
printf("学生数无效\n");
fclose(fp1);
return 1;
}
for (int i = 0; i < num_students; i++) {
Student student;
printf("请输入第 %d 个学生的姓名、学号、三科成绩:", i + 1);
scanf("%s %d %d %d %d", student.name, &student.id, &student.score1, &student.score2, &student.score3);
fwrite(&student, sizeof(Student), 1, fp1); // 写入文件
}
fclose(fp1);
// 从 f1.dat 中读取学生信息,并按总分排序后写入 f2.dat
FILE* fp2 = fopen("f2.dat", "wb");
if (!fp2) {
printf("无法打开文件 f2.dat\n");
return 1;
}
Student students[MAX_STUDENTS];
fseek(fp1, 0, SEEK_SET); // 将文件指针移到文件开始处
fread(students, sizeof(Student), num_students, fp1); // 读取所有学生信息
qsort(students, num_students, sizeof(Student), cmp_scores); // 按总分排序
fwrite(students, sizeof(Student), num_students, fp2); // 写入文件
fclose(fp2);
printf("操作成功完成\n");
return 0;
}
```
注意事项:
- 为了方便,这里使用了 `fwrite` 和 `fread` 函数进行二进制读写,每个学生信息占用固定的字节大小,如果需要更灵活的格式,可以使用类似 `fprintf` 和 `fscanf` 的函数。
- 由于要按总分排序,需要定义一个比较函数,并使用标准库中的 `qsort` 函数进行排序。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](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)