/*(2)有10个学生,每个学生的数据包括学号、姓名和3门课成绩,
1 计算每个学生的平均分,并将学生信息存入磁盘文件"stud"中;
2 输入一个学生的学号,在文件"stud"中,将该生删除,其结果仍保存在原文件"stud"中。*/
#include"stdio.h"
#include"stdlib.h"
struct Student{
int num;
char name[10];
float score[3];
float average;
};
int Input();
int Show();
int Delete();
int main()
{
int cho;
while(1)
{
printf("please chose the chose:\n");
printf("1.Input a student:\n");
printf("2.Show:\n");
printf("3.Delete a student:\n");
printf("4.Quit:\n");
scanf("%d",&cho);
switch(cho)
{
case 1:Input();break;
case 2:Show();break;
case 3:Delete();break;
case 4:return 0;
default:printf("please rechose:\n");
}
}
return 0;
}
int Input()
{
FILE *fp;
Student stu;
int i;
if((fp=fopen("stud","a"))==NULL)
{
printf("cannot open\n");
return 0;
}
printf("please input the stuents' num,name,score3:\n");
scanf("%d",&stu.num);
getchar();
scanf("%s",stu.name);
for(i=0;i<3;i++)
scanf("%f",&stu.score[i]);
stu.average=(stu.score[0]+stu.score[0]+stu.score[0])/3;
fwrite(&stu,sizeof(Student),1,fp);
fclose(fp);
return 0;
}
int Show()
{
int i;
Student stu;
FILE *fp;
if((fp=fopen("stud","r"))==NULL)
{
printf("cannot open\n");
return 0;
}
fread(&stu,sizeof(Student),1,fp);
while(!feof(fp))
{
printf("%d\t%10s\t",stu.num,stu.name);
for(i=0;i<3;i++)
printf("%.2f\t",stu.score[i]);
printf("%.2f\n",stu.average);
fread(&stu,sizeof(Student),1,fp);
}
fclose(fp);
return 0;
}
int Delete()
{
FILE *fp1,*fp2;
Student stu;
int num;
if((fp1=fopen("stud","r"))==NULL)
{
printf("cannot open\n");
return 0;
}
if((fp2=fopen("stud1","w"))==NULL)
{
printf("cannot open\n");
return 0;
}
printf("please input the num what you what delete\n");
scanf("%d",&num);
fread(&stu,sizeof(Student),1,fp1);
while(!feof(fp1))
{
if(stu.num!=num)
fwrite(&stu,sizeof(Student),1,fp2);
fread(&stu,sizeof(Student),1,fp1);
}
fclose(fp1);
fclose(fp2);
system("copy stud1 stud");
return 0;
}