10.6将第5题"stud"文件中的学生数据,按平均分进行排序处理,将已排序的学生数据存入一个新文件"stud_sort"中。

//C程序设计第四版(谭浩强)
//章节:第十章 对文件的输入输出 
//题号:10.6
//题目:将第5题"stud"文件中的学生数据,按平均分进行排序处理,将已排序的学生数据存入一个新文件"stud_sort"中。
#include <stdio.h>
#include <stdlib.h>
#define N 5
struct student
{
	int num;
	char name[10];
	float score[3];
	float aver;
};
int main()
{
	FILE *fp1,*fp2;
	int i=0,j;
	struct student stu0,stu[N];
	if((fp1=fopen("stud","rb"))==NULL)
	{
		printf("cannot open the file stud!\n");
		exit(0);
	}	//打开文件stud 
	printf("the original date:\n");
	printf("num name score1 score2 score3 average\n");
	for(i=0;i<N;i++)
	{
		fread(&stu[i],sizeof(struct student),1,fp1);
		printf("%-2d%5s%7.1f%7.1f%7.1f%7.1f\n",stu[i].num,stu[i].name,stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].aver);
	}	//将文件stud中的数据显示在屏幕上
	fclose(fp1);	//关闭文件stud 
	for(i=0;i<N-1;i++)		
	{
		for(j=i+1;j<N;j++)	//冒泡法排序 
		{
			if(stu[i].aver>stu[j].aver)		
			{
				stu0=stu[i];
				stu[i]=stu[j];
				stu[j]=stu0;
			}
		}
	}
	if((fp2=fopen("stud_sort","wb"))==NULL)
	{
		printf("cannot open the file stud_sort!\n");
		exit(0);
	}	//创建文件stud_sort
	for(i=0;i<N;i++)
	{
		if((fwrite(&stu[i],sizeof(struct student),1,fp2))!=1)
			printf("flie write error!\n");
	}	//将排序后的数据写进文件stud_sort
	fclose(fp2);	//关闭文件stud_sort
	if((fp2=fopen("stud_sort","wb"))==NULL)
	{
		printf("cannot open the file stud_sort!\n");
		exit(0);
	}	//重新打开文件stud_sort
	printf("the sorted date:\n");
	printf("num name score1 score2 score3 average\n");
	for(i=0;i<N;i++)
	{
		fread(&stu[i],sizeof(struct student),1,fp2);
		printf("%-2d%5s%7.1f%7.1f%7.1f%7.1f\n",stu[i].num,stu[i].name,stu[i].score[0],stu[i].score[1],stu[i].score[2],stu[i].aver);
	}	//将文件stud_sort中的数据显示在屏幕上以验证
	fclose(fp2);
	return 0; 	 
}
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值