C++读写文件及容器list基本操作
大家在开始入门C/C++时,都要练习个学生管理系统啥的,主要都为了进一步掌握所学知识,并能使用这些知识。其中这个小项目的重难点就在数据的操作了,其中如何将数据保存到文件中及如何将文件中的内容读出并存放到list中。
读写文件基本思路是,打开文件,然后进行读写操作,在关闭文件。其中读写文件我是选择了fscanf()和fprintf(),
使用这一对函数,我个人感觉,写入的文件可视性较强,在这里比二进制读写fwrite()和fread()好。
参考代码如下:
1.读出文件存放list中
typedef list<Student>Stu;
bool DataOper::ReadFileToList(Stu &stu)
{
FILE *fp = NULL;
//1.fopen
if( (fp = fopen("student.txt","r")) == NULL)
{
cout<<"open File Error"<<endl;
return false;
}
//2.read File
while(1)
{
fscanf(fp,"%d %s %d %c %d %d %d %d %d",&student.Id,student.Name,&student.passwd,&student.Sex,&student.Age,
&student.Class,&student.Math,&student.English,&student.Chinese);
if(feof(fp))
{
break;
}
stu.push_back(student);
}
//3.fclose
fclose(fp);
return true;
}
2.将list数据写入文件
bool DataOper::WriteFile(Stu &stu)
{
FILE *fp = NULL;
Stu::iterator iStu = stu.begin();
//1.fopen
if( (fp = fopen("student.txt","w")) == NULL)
{
cout<<"open File Error"<<endl;
return false;
}
//2.write File
while(iStu != stu.end())
{
fprintf(fp,"%d %s %d %c %d %d %d %d %d\n",iStu->Id,iStu->Name,iStu->passwd,iStu->Sex,iStu->Age,iStu->Class,
iStu->Math,iStu->English,iStu->Chinese);
iStu++;
}
//3.fclose
fclose(fp);
return true;
}