新手上路,问一问结构体文件的问题,如何按条件把文件中符合的结构体全部输出到屏幕?
#include "stdio.h"#include "stdlib.h"
typedef struct student
{
int num;
char name[20];
char s;
int age;
}STU;
void input(STU *p)
{
printf("请输入学号:");
scanf("%d",&p->num);
getchar();
printf("请输入姓名:");
gets(p->name);
printf("请输入性别:");
scanf("%c",&p->s);
getchar();
printf("请输入年龄:");
scanf("%d",&p->age);
}
void save(char *filename,STU *p)
{
FILE *fp;
if((fp=fopen(filename,"ab"))==NULL)
{
fp=fopen(filename,"wb");
}
fwrite(p,sizeof(STU),1,fp);
fclose(fp);
}
STU *query(char *filename,int age,STU *p)
{
FILE *fp;
if((fp=fopen(filename,"rb"))==NULL)
return NULL;
while(!feof(fp))
{
fread(p,sizeof(STU),1,fp);
while(p->age<=age)
{
return p;
fclose(fp);
}
}
fclose(fp);
return NULL;
}
main()
{
char ch;
char filename[80];
int age;
STU sc,*sp=≻
printf("请输入文件的名字:");
gets(filename);
printf("是否现在输入数据(y/n):");
ch=getchar();
getchar();
while(ch=='y'||ch=='Y')
{
input(sp);
save(filename,sp);
printf("\n继续(y/n):");
ch=getchar();
getchar();
}
printf("\n请输入要查询的年纪:");
scanf("%d",&age);
if(query(filename,age,sp)!=NULL)
{
printf("%-7d%-20s%-10c%-7d\n",sp->num,sp->name,sp->s,sp->age);
}
else
{
printf("\n NO result\n");
}
}