【C语言】练习fread和fwrite//并用链表存储高分学生信息

fwrite是二进制方式写入,写入后的文件不是文本格式,不能用文本编辑器打开,只有纯文本文件才能用记事本打开,这是二进制文件 。

#include<stdio.h> 
#include<stdlib.h>
#define N 10
/*求最高分学生*/ 
typedef struct student
{
	int num;
	char name[10];
	char sex;
	float score;
	struct student *next;
}STU;
int main()
{
	STU stu,stu_max;int i;
	FILE *fp;
	if((fp=fopen("file_test.dat","wb"))==NULL)
	{
		printf("cannot open!");
	}
	stu_max.score=0;
	for(i=0;i<N;i++)
	{
		scanf("%d %s %c %f",&stu.num,stu.name,&stu.sex,&stu.score);
		stu.next=NULL;
		if(fwrite(&stu,sizeof(STU),1,fp)!=1)
		  printf("writing error!");
		if(stu_max.score<stu.score)
		{
			stu_max=stu; 
		}
	}
	fclose(fp);
	if((fp=fopen("file_test.dat","rb"))==NULL)
	{
		printf("cannot open!");
	}
	
	STU *head=NULL,*p;
	p=head;
	
	for(i=0;i<N;i++)
	{
		fread(&stu,sizeof(STU),1,fp);
		if(stu_max.score==stu.score)
		{
			p=(STU *)malloc(sizeof(STU));
			*p=stu;p->next=head;head=p;//头部插入
		}
	}fclose(fp);
	printf("------输出------");
	while(p!=NULL)
	{
		printf("\n%d %s %c %0.1f\n",p->num,p->name,p->sex,p->score);
		p=p->next;
	}
	return 0;
}
/*
01 min f 99
02 yan f 100
03 jie f 99
04 wang m 100
05 xiao m 90
06 mao f 91
07 dong m 100
08 ma m 93
09 liu f 95
10 peng m 100
*/

效果如下 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

*Min*

写的不好多多包涵~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值