C++读写文件保存至容器list中

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;
}

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值