操作文件的三大类
1、ofstream 写文件
2、ifstream 读文件
3、fstream 读写文件
写文件
include <fstream>
ostream ofs;
ofs.open("文件路径",打开方式);
ofs<<"写入的文件内容"
ofs.close();
打开方式 | 解释 |
---|---|
ios::in | 读文件打开 |
ios::out | 写文件打开 |
ios::ate | 初始到文件尾 |
ios::app | 追加 |
ios::trunc | 先删除再创建 |
ios::binary | 二进制 |
读文件
include<fstream>
ifstream ifs;
ifs.open("文件路径",ios::in);
if(!ifs.is_open())
{
cout<<"文件打开失败"<<endl;
return ;
}
读文件的四种方式
第一种
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;
}第四种
char c;
while((c=ifs.get())!=EDF)
{
cout<<c;
}