我们这里数据格式为
201911606 liu 1.1 1.2 99
201911607 wang 1.2 1.3 98
……
fwrite写入文件是二进制代码形式,所以用文本打开为乱码,这时候我们可以用fprintf代替
fwrite效果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200425154530105.png)
乱码
fprintf效果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200425154624566.png)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct grade
{
char id[20];
char name[10];
double n1, n2;
int rank;
}stu1[200];
typedef struct grade *pStu;
int comp1(const void *a, const void *b);
int main()
{
int i, j, count = 0;
FILE *fp1, *fp2;
fp1 = fopen("grade.txt", "r");
while((fscanf(fp1,"%s%s%lf%lf%d\n", stu1[count].id, stu1[count].name, &stu1[count].n1, &stu1[count].n2, &stu1[count].rank)) != -1)
count++;
rewind(fp1);
fclose(fp1);
qsort(stu1, count, sizeof(struct grade), comp1);
fp2 = fopen("output.txt", "w");
for (i = 0; i < count; i++)
fprintf(fp1, "%s %s %lf %lf %d\n", stu1[i].id, stu1[i].name, stu1[i].n1, stu1[i].n2, stu1[i].rank);
rewind(fp2);
fclose(fp2);
return 0;
}
int comp1(const void *a, const void *b)
{
pStu p1, p2;
p1 = (pStu)a;
p2 = (pStu)b;
return strcmp(p1, p2);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)