一、实验目的和要求
(1)掌握文件、文件指针的概念。
(2)了解文件操作的一般步骤。
(3)熟练掌握文件的各种操作,包括文件的打开、关闭、读/写等。
二、实验内容和步骤
- 有5个学生,每个学生有3门课的成绩,从键盘输入学号、姓名及3门课的成绩,将这些原始数据存放在磁盘文件bigdata.txt中。
假设5名学生的学号、姓名和3门课的成绩如下:
001 Wang 90,89,79
002 Li 99,88,77
003 Zhao 98,87,76
004 Zhang 100,77,99
005 Yuan 45,78,93
2.将上题bigdata.txt文件中的数据,按平均分进行降序处理,并将已排序的学生数据存入一个新文件stud_sort.txt中。
参考代码:我设定了只输入3个学生的信息,大家也可以设定输入多少个学生的信息。该程序仅供参考。
#include<stdio.h>
#include<conio.h>
struct student{
char XH[20];
char name[12];
double score[3];
double ave;
};
void input(struct student s[],int n)
{
int i,j; FILE *fp;
double ave=0;
fp=fopen("d:\\lcy\\bigdata.txt","wb");
for(i=0;i<3;i++)
{
gets(s[i].XH);
gets(s[i].name);
for(j=0;j<3;j++)
{
scanf("%lf",&s[i].score[j]);
s[i].ave+=s[i].score[j];
}
s[i].ave/=3;
fwrite(&s[i],sizeof(s[i]),1,fp);
getchar();
}
fclose(fp);
}
void sort_ave(struct student s[],int n)
{
int i,j,p;
struct student t;
FILE *fp1;
for(i=0;i<n-1;i++)
{
p=i;
for(j=i+1;j<n;j++)
if(s[j].ave>s[p].ave)
p=j;
if(p!=i)
{
t=s[i];
s[i]=s[p];
s[p]=t;
}
}
fp1=fopen("d:\\lcy\\stud_sort.txt","wb");
for(i=0;i<n;i++)
fwrite(&s[i],sizeof(s[i]),1,fp1);
fclose(fp1);
}
void output(struct student s[],int n)
{
FILE *fp;int i,j;
fp=fopen("d:\\lcy\\stud_sort.txt","rb");
for(i=0;i<3;i++)
{
fread(&s[i],sizeof(s[i]),1,fp);
puts(s[i].XH);
puts(s[i].name);
for(j=0;j<3;j++)
printf("%lf\t",s[i].score[j]);
printf("\n");
}
fclose(fp);
}
int main()
{
struct student s[3];
FILE *fp; int i;
input(s,3);
fp=fopen("d:\\lcy\\bigdata.txt","rb");
for(i=0;i<3;i++)
fread(&s[i],sizeof(s[i]),1,fp);
sort_ave(s,3);
output(s,3);
}