10. 文件的读写

发布于:2024-09-18 ⋅ 阅读:(147) ⋅ 点赞:(0)

10.1 文本文件

操作文件三大类:

  • ofstream:写操作
  • ifstream:读操作
  • fstream:读写操作
打开方式 解释
ios::in 为了读文件而打开文件
ios::out 为了写文件而打开文件,如果当前文件存在则清空当前文件在写入
ios::app 追加方式写文件
ios::trunc 如果文件存在先删除,在创建
ios::ate 打开文件之后令读写位置移至文件尾端
ios::binary 二进制方式

文件打开方式可以配合使用,利用|操作符
例如:利用二进制方式写文件,ios::binary|ios::out

10.1.1 写文件

  • 普通写文件
#include<fstream> // 文件头
ofstream ofs;// 创建流对象
ofs.open("path",打开方式);
ofs<<"写入数据"<<endl;
ofs.close();// 关闭文件
  • 二进制写文件
#include<fstream> // 文件头
ofstream ofs;// 创建流对象
ofs.open("path",ios::out|ios::binary);
Person p={"张三",18};
ofs.write((const char *)&p,sizeof(Person));//Person 自定义类
ofs.close();// 关闭文件

10.1.2 读文件

  • 普通读文件
#include<fstream> // 文件头
ifstream ifs;// 创建流对象
ifs.open("path",打开方式);
if(!ifs.open()){
	cout<<文件打开失败!<<endl;
	return
}
// 四种读取方法
// 第一种方法
//char buf[1024]={0};
//while(ifs>>buf){
	//cout<<buf<<endl;
//}
// 第二种方法
//char buf[1024]={0};
//while(ifs.getline(buf,size(buf))){
	//cout<<buf<<endl;
//}
// 第三种方法
//string buf;
//while(getline(ifsbuf){
	//cout<<buf<<endl;
//}

// 第四种方法,比较少用
//char c;
//while((c=ifs.get())!EOF){
	//cout<<c<<endl;
//}
ifs.close()
  • 二进制读文件
#include<fstream> // 文件头
ofstream ofs;// 创建流对象
ofs.open("path",ios::int|ios::binary);
Person p={"张三",18};
if(!ifs.open()){
	cout<<文件打开失败!<<endl;
	return
}
ofs.read((const char *)&p,sizeof(Person));//Person 自定义类
cout<<p.name<<":"<<p.age<<endl;
ofs.close();// 关闭文件

网站公告

今日签到

点亮在社区的每一天
去签到