现在的位置: 首页 > 综合 > 正文

程序二

2013年05月16日 ⁄ 综合 ⁄ 共 1120字 ⁄ 字号 评论关闭

#include<stdio.h>
#include<stdlib.h>

#define M 5
#define N 3

struct student
{
long num;
char name[20];
int score[N];
int avg;
}stud[M];
void input(struct student *p)
{
int i,j;
printf("Input the information:/n/n");
for(i=0;i<M;i++,p++)
{
printf("num:");
scanf("%ld",&p->num);
getchar();
printf("name:");
scanf("%s",p->name);
printf("Input score:/n");
for(j=0;j<N;j++)
 scanf("%d",&p->score[j]);
p->avg=(p->score[0]+p->score[1]+p->score[2])/3;
}
}

void save(char *filename)
{
FILE *fp;
int i;
if((fp=fopen(filename,"wb"))==NULL)
{
printf("Can not open this file./n");
exit (1);
}
for(i=0;i<M;i++)
   if(fwrite(&stud[i],sizeof(struct student),1,fp)!=1)
    printf("Can not write this file./n");
fclose(fp);
}

void output(char *filename)
{
FILE *fp;
int i;
if((fp=fopen(filename,"rb"))==NULL)
{
printf("Can not open this file./n");
exit (1);
}
for(i=0;i<M;i++)
   if(fread(&stud[i],sizeof(struct student),1,fp)!=1)
    printf("Can not write this file./n");
   else printf("Num:%ld  Name:%s  score:%d %d %d  Avg:%d/n",stud[i].num,stud[i].name,stud[i].score[0],stud[i].score[1],stud[i].score[2],stud[i].avg);
fclose(fp);
}

void main()
{
char fn[30];
clrscr();
input(stud);
printf("Input a filename:");
scanf("%s",fn);
save(fn);
output(fn);
getch();

抱歉!评论已关闭.