#include <stdio.h>
struct StudentType/定义结构体类型/
{
char no[10],name[10];
double spec1,spec2,spec3,spec4;
double totalScore;
};
void WriteToFile(void);/函数声明,向文件写入数据/
void ReadFromFile(void);/函数声明,从文件读出数据/
int main()
{
int select;
printf("1.录入成绩 2.输出成绩 0.退出\n");
printf("请输入要执行的操作:");
scanf("%d",&select);
switch(select)
{
case 1: WriteToFile();break;/录入考生成绩并写入文件/
case 2: ReadFromFile();break;/从文件读取考生成绩并输出/
deafault: printf("退出程序!");break;
}
return 0;
}
void WriteToFile(void)/函数定义,没有参数且没有返回值/
{
FILE *fp=NULL;/定义文件指针并初始化为空/
struct StudentType stu;
char flag='y';/继续输入标志/
fp=fopen("stu_grade.txt","a");
while((flag=='y'||flag=='Y'))
{
printf("请输入考生号和姓名:");
scanf("%s%s",stu.no,stu.name);
printf("请输入考生各科成绩:");
scanf("%lf%lf%lf%lf",&stu.spec1,&stu.spec2,&stu.spec3,&stu.spec4);
stu.totalScore=stu.spec1+stu.spec2+stu.spec3+stu.spec4;
fprintf(fp,"%10s%10s",stu.no,stu.name);/以指定格式写文件/
fprintf(fp,"%8.2f%8.2f%8.2f",stu.spec1,stu.spec2,stu.spec3);
fprintf(fp,"%8.2f%8.2f",stu.spec4,stu.totalScore);
fputc('\n',fp);/将换行符写入文件/
fflush(stdin);/清空键盘缓冲区/
printf("继续输入吗?继续请输入y或Y:");
scanf("%c",&flag);
}
fclose(fp);/关闭文件/
}
void ReadFromFile(void)/函数定义,没有参数且没有返回值/
{
FILE *fp=NULL;/定义文件指针并初始化为空/
struct StudentType stu;
fp=fopen("stu_grade.txt","r");/以只读方式打开文件/
printf(" 考生姓名 总分\n");/打印表头/
while(!feof(fp))/当文件未结束时/
{
fscanf(fp,"%s%s",stu.no,stu.name);/以指定格式读文件/
fscanf(fp,"%lf%lf%lf",&stu.spec1,&stu.spec2,&stu.spec3);
fscanf(fp,"%lf%lf",&stu.spec4,&stu.totalScore);/读取行末回车符/
printf("%10s%8.2f\n",stu.name,stu.totalScore);
}
fclose(fp);/关闭文件/
}