环境:ide:Mac+clion
视频链接:
https://www.bilibili.com/video/BV1Hb411Y7E5?p=5
文件操作
文件操作:持久化数据。
文件存储形式:文本文件/二进制文件
读文件:ifsteam 读文件
写文件:ofstream 输出到文件中。
读写操作:fsteam
写文件步骤:
1.包含头文件 #include <fstream>
2.创建流对象。
3.打开文件。ios::in 读文件 ios::out 写文件 ios::binary 二进制
4.写文件。
5.关闭流。
#include <fstream> //包含头文件#include<ostream>
void writeFile(){
ofstream ofs;//创建流对象
ofs.open("info.txt",ios::out);
ofs<<"姓名:sheik"<<endl;
ofs<<"性别:male"<<endl;
ofs<<"年龄:20"<<endl;
ofs.close();
}
void readFile() {
ifstream ifs;//创建流对象。
ifs.open("info.txt",ios::in);
if(!ifs.is_open()){ //判断文件是否打开成功。
cout << "文件打开失败。"<<endl;
return;
}
//4.四种方式读文件。
//第一种方式:
// char buf[1024] = {0};
// while(ifs >> buf){
// cout << buf<<endl;
// }
//第二种方式:
char buf[1024] = {0};
while(ifs.getline(buf,sizeof (buf))){
cout << buf<< endl;
}
//第三种
// string buf;
// while(getline(ifs,buf)){
// cout << buf<<endl;
// }
//第四种:EOF 文件尾部的标志。
// char c;
// while((c=ifs.get())!= EOF){
// cout << c<<endl;
// }
//5.关闭流。
ifs.close();
}
通过二进制的方式读写:
class Person{
public:
string m_Name;
int m_Age;
};
void writeBinary(){
ofstream ofs;
ofs.open("bean.txt",ios::out | ios::binary);
Person person;
person.m_Name = "张三";
person.m_Age = 18;
ofs.write((const char *)&person,sizeof (person));
ofs.close();
}
void readBinary(){
ifstream ifs;
ifs.open("bean.txt",ios::in | ios::binary);
if (!ifs.is_open()){
cout << "文件打开失败!"<<endl;
return ;
}
// char ch;
// ifs >>ch;
// if (!ifs.eof()){
// cout << "文件不为空!"<<endl;
// //return ;
// }
Person person ;
ifs.read((char *)&person,sizeof (person));
cout << person.m_Name << "," << person.m_Age<<endl;
ifs.close();
}