假设有10位同学,各有3门课程的成绩。从键盘输入每位同学的学号、姓名和3门课程的成绩,然后把数据保存到磁盘文件,再将磁盘文件中的学生信息读入并显示

代码
#include<stdio.h>
#include
<stdlib.h>
#define N 5
struct student
{
char sno[10];
char name[10];
int grade[3];
};

void write()
{
FILE
*fp;
struct student s[10];
int i,j;

if((fp=fopen("test.txt","w"))==NULL)
{
printf(
"无法打开文件。\n");
exit(
1);
}

printf(
"请输入数据:\n");
for(i=0;i<N;i++)
{
printf(
"请输入学号:");
scanf(
"%s",s[i].sno);
printf(
"请输入3门课的成绩:");
for(j=0;j<3;j++)
scanf(
"%d",&s[i].grade[j]);
printf(
"请输入姓名:");
scanf(
"%s",s[i].name);

}

for(i=0;i<N;i++)
fprintf(fp,
"%s %s %d %d %d ",s[i].sno,s[i].name,s[i].grade[0],s[i].grade[1],s[i].grade[2]);
fclose(fp);

}

void read()
{
FILE
*fp;
struct student s;
if((fp=fopen("test.txt","r"))==NULL)
{
printf(
"无法打开文件。\n");
exit(
1);
}

printf(
"学号\t姓名\t语文\t数学\t英语\n");
while(fscanf(fp,"%s %s %d %d %d",s.sno,s.name,&s.grade[0],&s.grade[1],&s.grade[2])!=EOF)
{
printf(
"%-5s%-10s\t%4d\t%4d\t%4d\n",s.sno,s.name,s.grade[0],s.grade[1],s.grade[2]);
}

fclose(fp);
}

void main()
{
write();
read();

}

 

posted @ 2010-02-24 16:12  齐心  Views(5143)  Comments(0Edit  收藏  举报