C++读写文件保存至容器list中
来源:互联网 发布:finale打谱软件汉化 编辑:程序博客网 时间:2024/05/29 19:07
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;
}
- C++读写文件保存至容器list中
- 解析xml文件保存到List中
- C#中读写INI文件
- C#中读写INI文件
- C/C++中读写文件
- C 数据保存文件中
- 如何在C#中读写INI文件
- 如何在C#中读写INI文件
- 在C#中读写INI文件
- 如何在C#中读写INI文件
- 如何在C#中读写INI文件
- 在C#中读写INI文件
- 如何在C#中读写INI文件
- 如何在C#中读写INI文件
- 在C#中读写Excel文件
- 如何在C#中读写INI文件
- 如何在C#中读写INI文件
- 如何在C#中读写INI文件
- 可子类化设计
- Awesome Computer Vision
- C语言可变参数的原理
- springmvc 中关于“内容协商”的小记
- java根据手机号获取归属地
- C++读写文件保存至容器list中
- Win7 Eclipse Hadoop2.4插件配置
- web前端学习-kindeditor
- 机器学习实战笔记之三(决策树)
- 《剑指offer》——矩阵中的路径
- Leetcode || Implement strStr()
- 使用ActionMode实现ListView的多选功能
- method / function
- paip.解决 数据库mysql增加列 字段很慢添加字段很慢