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
*/
效果如下