文件操作
程序运行的数据属于临时数据,一旦结束就释放。
所以需要通过文件将数据持久化
c++ 文件操作包含头文件
文件类型:
1.文本文件 :ASCII码存储
2.二进制文件
操作文件的三大类:
1.ofstream 写操作
2.ifstream 读操作
3.fstream 读写操作
写文件
文本文件
1.包含头文件 #include
2.创建流对象 ofstream ofs;
3.打开文件 ofs.open(“文件路径”,打开方式);
4.写数据 ofs << “写入的数据”;
5.关闭文件 ofs.close();
文件打开方式
使用程序:
//1.包含头文件
#include <fstream>
#include <stdio.h>
#include <iostream>
using namespace std;
void test01(){
//2.创建流对象
ofstream ofs;
//3.指定打开方式
ofs.open("test.txt",ios::out);
//4.写内容
ofs<<"姓名:张三"<<endl;
//5.关闭文件
ofs.close();
}
int main(){
test01();
return 0;
}
## ```读文件
步骤:
1.包含头文件
2. 创建流对象
ifstream ifs;
3. 打开文件并且判断文件是否打开成功
ifs.open("文件路径","打开方式");
4. 读数据 四种读取方式
5. 关闭文件
```cpp
//1.包含头文件
#include <fstream>
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
void test01(){
//2.创建流对象
ifstream ifs;
//3.指定打开方式
ifs.open("test.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;
//第三种
//string buf;
//while(getline(ifs,buf))
//cout <<buf<<endl;
//第四种不建议
char c;
while((c = ifs.get())!=EOF)//文件尾标志
cout << c;
//5.关闭文件
ifs.close();
}
int main(){
test01();
return 0;
}
二进制文件
打开方式指定为ios::binary
写文件
代码:
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
//二进制文件 写文件
class Person{
public :
char m_Name[64];//姓名
int m_Age;//年龄
};
void test01(){
//创建输出流对象
ofstream ofs;
//打开文件
ofs.open("person.txt",ios::out | ios :: binary);
Person p ={"张三",18};
//写文件,最好char数组
ofs.write( (const char *)&p ,sizeof(Person) );
//关闭文件
ofs.close();
}
int main(){
test01();
return 0;
}
读文件
代码
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
//二进制文件 读文件
class Person{
public :
char m_Name[64];//姓名
int m_Age;//年龄
};
void test01(){
//创建输出流对象
ifstream ifs;
//打开文件 ,判断是否打开成功
ifs.open("person.txt",ios::in | ios :: binary);
if(!ifs.is_open())
{
cout <<"文件打开失败";
return ;
}
Person p ;
//读文件,最好char数组
ifs.read( ( char *)&p ,sizeof(Person) );
cout <<"姓名:"<<p.m_Name<<endl;
cout <<"年龄:"<<p.m_Age<<endl;
//关闭文件
ifs.close();
}
int main(){
test01();
return 0;
}