您的位置:首页 > 其它

利用FILE结构对文件进行操作

2010-05-26 17:27 453 查看
//利用FILE结构对文件进行操作
//输入若干个学生的数据(包括学号、姓名和成绩)
//将数据存放在Student.txt文件中
//从Student.txt文件中读取所有数据并显示出来
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
struct student
{
char num[8];
char name[20];
float score;
};
void main()
{
student from[100],to[100]; //定义结构体数组,from用于存放输入的数据的,to用于存放从文件中读取的数据
int n;
cout<<"输入学生的人数:";
cin>>n;
for(int i=0;i<n;i++) //输入学生数据,并存放到from数组中
{
cout<<"输入第"<<i+1<<"个学生的学号、姓名、成绩:";
cin>>from[i].num>>from[i].name>>from[i].score;
}
FILE *write,*read; //定义两个文件指针,分别用于对文件的写和读
if((write=fopen("Student.txt","w"))==NULL) //判断目标文件是否成功打开
{
cout<<"cannot open this file./n"<<endl;
exit(0);
}
for(i=0;i<n;i++) //将学生的数据写到文件中
{
if(fwrite(&from[i],sizeof(student),1,write)!=1) //判断原文件是否成功打开
{
cout<<"file write error./n"<<endl;
exit(0);
}
}
fclose(write);
if((read=fopen("Student.txt","r"))==NULL)
{
cout<<"cannot open this file./n"<<endl;
exit(0);
}
cout<<"学号/t姓名/t分数"<<endl;
for(i=0;i<n;i++) //将文件中的数据读出,并显示在屏幕上
{
fread(&to[i],sizeof(student),1,read);
cout<<to[i].num<<'/t'<<to[i].name<<'/t'<<to[i].score<<endl;
}
fclose(read);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: