从文件中读取学生信息,按照平均分顺序插入学生节点,保存到原文件中

#include<stdio.h>
#include<stdlib.h>
#define M 6
#define N 3
struct student{
	int num;
	char name[20];
	float score[3];
	float ave;
}cla1[M+1],cla2[M+1],temp,st1;
//从文件中读取学生信息,按照平均分插入学生节点
void main(){
	FILE *fp;
	int i,j;
	float ave = 0;
	if((fp = fopen("stu_sort","rb")) == NULL){
		printf("error 201!\n");
		exit(0);
	}
	printf("原始数据:\n");
	for(i = 0;i < M;i++){
		fread(&cla1[i],sizeof(struct student),1,fp);
		printf("%-5d,%-7s",cla1[i].num,cla1[i].name);
		for(j = 0;j < N;j++)
			printf("%-6.2f",cla1[i].score[j]);
		printf("%-6.2f",cla1[i].ave);
		printf("\n");
	}
	fclose(fp);
	printf("请输入需要插入的学生节点数据:\n");
	scanf("%d,%s",&st1.num,st1.name);
	for(j = 0;j < N;j++){
		scanf("%f",&st1.score[j]);
		ave += st1.score[j];
	}
	st1.ave = ave/N;
	cla1[M] = st1;
	for(i = 0;i < M;i++)
		for(j = i+1;j < M+1;j++)
			if(cla1[i].ave < cla1[j].ave){
				temp = cla1[i];
				cla1[i] = cla1[j];
				cla1[j] = temp;
			}
	if((fp = fopen("stu_sort","wb")) == NULL){
		printf("error 202!\n");
		exit(0);
	}
	for(i = 0;i <= M;i++)
		fwrite(&cla1[i],sizeof(struct student),1,fp);
	fclose(fp);
	if((fp = fopen("stu_sort","rb")) == NULL){
		printf("error 203!\n");
		exit(0);
	}
	for(i = 0;i <= M;i++)
		fread(&cla2[i],sizeof(struct student),1,fp);
	fclose(fp);
	printf("插入后的数据:\n");
	for(i = 0;i <= M;i++){
		printf("%-5d,%-7s",cla2[i].num,cla2[i].name);
		for(j = 0;j < N;j++)
			printf("%-6.2f",cla2[i].score[j]);
		printf("%-6.2f",cla2[i].ave);
		printf("\n");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值