您的位置:首页 > 编程语言 > C语言/C++

用文件简单的的学生信息管理(第一次用,好多不懂的地方,大家多指正)

2014-12-31 23:04 302 查看
/*(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C语言