文件(作业)
作者:互联网
#include <stdio.h>
#include<Stdlib.h>
#define N 30
typedef struct date
{
int year;
int month;
int day;
} DATE;
typedef struct student
{
long studentID;//学号
char studentName[10];
char studentSex[2];
}STUDENT;
typedef struct award
{
long studentID;//学号
char honor[30];
}AWARD;
typedef struct result
{
long studentID;//学号
char studentName[10];
char studentSex[2];
char honor[30];
}RESULT;
void InputInformation(STUDENT stu[],int n)//从键盘输入n个学生的信息到结构体数组stu中
{
int i,j;
for(i=0;i<n;i++)
{
printf("Input record %d:\n",i+1);
scanf("%ld",&stu[i].studentID);
scanf("%s",&stu[i].studentName);
scanf(" %s",&stu[i].studentSex);
}
}
void InputAward(AWARD awa[],int n)//从键盘输入n个学生的奖励信息到数组awa中
{
int i,j;
for(i=0;i<n;i++)
{
printf("Input award %d:\n",i+1);
scanf("%ld",&awa[i].studentID);
scanf("%s",&awa[i].honor);
}
}
void WritetoFile1(STUDENT stu[],int n)//文件student.txt
{
FILE *fp;
if((fp=fopen("student.txt","w"))==NULL) //以写方式打开文件
{
printf("Failure to open student.txt!\n") ;
exit(0);
}
fwrite(stu,sizeof(STUDENT),n,fp);//按数据块写文件
fclose(fp);
}
void WritetoFile2(AWARD awa[],int n)//文件award.txt
{
FILE *fp;
if((fp=fopen("award.txt","w"))==NULL) //以写方式打开文件
{
printf("Failure to open award.txt!\n") ;
exit(0);
}
fwrite(awa,sizeof(AWARD),n,fp);//按数据块写文件
fclose(fp);
}
int ReadfromFile1(STUDENT stu[])//从文件中读取学生的信息到结构体数组stu中并返回学生数
{
FILE *fp;
int i;
if((fp=fopen("student.txt","r"))==NULL) //以读方式打开文件
{
printf("Failure to open student.txt!\n") ;
exit(0);
}
for(i=0;!feof(fp);i++)
{
fread(&stu[i],sizeof(STUDENT),1,fp); //按数据块读文件
}
fclose(fp);
printf("Total students is %d.\n",i-1);
return i-1;
}
int ReadfromFile2(AWARD awa[])//从文件中读取学生的奖励信息到结构体数组awa中并返回学生数
{
FILE *fp;
int i;
if((fp=fopen("award.txt","r"))==NULL) //以读方式打开文件
{
printf("Failure to open award.txt!\n") ;
exit(0);
}
for(i=0;!feof(fp);i++)
{
fread(&awa[i],sizeof(AWARD),1,fp); //按数据块读文件
}
fclose(fp);
printf("Total awards is %d.\n",i-1);
return i-1;
}
void PrintfResult(STUDENT stu[],AWARD awa[],int n)
{
int i,j;
for(i=0;i<n;i++)
{
printf("%10ld %8s %3s %10s\n",stu[i].studentID,stu[i].studentName,stu[i].studentSex,awa[i].honor);
}
}
void Research(STUDENT stu[],AWARD awa[],int ID)
{
int i=0,j=0;
while(stu[i].studentID!=ID) i++;
while(awa[j].studentID!=ID) j++;
printf("ID为%d的学生信息为:",ID);
printf("%10ld %8s %3s %10s\n",stu[i].studentID,stu[i].studentName,stu[i].studentSex,awa[j].honor);
}
int main()
{
STUDENT stu[N];
AWARD awa[N];
RESULT res[N];
int n,ID;
printf("学生人数n:");
scanf("%d",&n);
printf("输入学号 姓名 性别 :\n");
InputInformation(stu,n);
printf("输入奖励信息:\n") ;
InputAward(awa,n);//从键盘输入n个学生的奖励信息到数组awa中
WritetoFile1(stu,n);
WritetoFile2(awa,n);
// n=ReadfromFile1(stu);
// PrintfResult(stu,awa,n);
printf("输入搜索的学号:");
scanf("%d",&ID) ;
Research(stu,awa,ID);
return 0;
}
标签:文件,typedef,studentID,struct,int,作业,long,char 来源: https://blog.csdn.net/weilaikeqiqi/article/details/121218473