C语言已知file1.dat中存储了5名学生信息,从file1.dat中读出学生信息,将学生信息按分数降序排序后写入file2.dat. 学生信息定义如下: struct stu{ int sno; char[20] sname; double score; } 【输入形式】 无 【输出形式】 文件file2.dat
时间: 2024-02-12 19:06:46 浏览: 28
好的,这是一个比较典型的文件读写排序的问题,你可以参考下面的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stu{
int sno;
char sname[20];
double score;
};
int cmp(const void *a, const void *b) {
struct stu *s1 = (struct stu*)a;
struct stu *s2 = (struct stu*)b;
if (s1->score < s2->score) {
return 1;
} else if (s1->score > s2->score) {
return -1;
} else {
return 0;
}
}
int main() {
FILE *fp1, *fp2;
struct stu s[5];
int i;
fp1 = fopen("file1.dat", "rb");
fp2 = fopen("file2.dat", "wb");
if (fp1 == NULL || fp2 == NULL) {
printf("File open error!\n");
return 0;
}
fread(s, sizeof(struct stu), 5, fp1); // 从文件fp1中读取5个学生信息
qsort(s, 5, sizeof(struct stu), cmp); // 按照分数降序排序
fwrite(s, sizeof(struct stu), 5, fp2); // 将排序后的学生信息写入文件fp2
fclose(fp1);
fclose(fp2);
return 0;
}
```
这个程序中,我们定义了一个结构体`struct stu`来存储学生信息。然后,我们使用`fopen`函数打开文件`file1.dat`和`file2.dat`,并通过`fread`函数从`file1.dat`中读取5个学生信息到`s`数组中。接着,我们使用`qsort`函数对`s`数组进行按照分数降序排序,排序的比较函数是`cmp`。最后,我们通过`fwrite`函数将排序后的学生信息写入`file2.dat`文件中。最后别忘了关闭文件指针。