C++文本操作文件-读、写文件

文件操作
程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放
通过文件可以将数据持久化
--------------------------
C++中对文件操作需要包含头文件<fstream>

文件类型分为:
文本文件:文件以文本的ACSII码形式存在在计算机中
二进制文件:文件以文本的形式存在计算机中

操作类文件的三大类:
ofsteam:写操作output(输出)
ifsteam:读操作input(输入)
fsteam:读写操作

文本文件:
写文件步骤如下:
1.创建一个头文件
#include<fstream>
2.创建流对象
fstream ofs;
3.打开文件
ofs.open("demo1.txt",ios::in);
4.写数据
ofs("写入的数据");
5.关闭
ofs.close();

文件打开方式:
ios::in为读文件打开
ios::out为写文件打开
ios::ate初始位置:文件尾
ios::app 追加方式写文件
Ios::trunc 如果文件存在会删除,创建新文件
ios::binary 二进制文件
===============================
demo1
文本文件中写文件

#include<fstream>
void test01(){

1.创建流对象
fstream ofs;
打开的方式
ofs.open("demo.txt",ios::out);
写入数据
ofs<<"姓名:关羽"<<endl;
ofs<<"阵营:蜀国"<<end;
ofs<<"武器:青龙偃月刀"<<endl;
ofs<<"兵种:刀斧兵"
关闭
ofs.close();
}

-------------------------------------
读文件

读文件步骤:
1.包含头文件
#include<ifsteam>
2.创建旒对象
ifsteam ifs;
3.打开文件并判断是否打开成功
ifs.open("demo1.txt",ios::in);
4.读数据
ifs<<""<<endl;
5.关闭
ifs.close();

=======================================
读文件
demo2
#include<fstream>

test01(){
fstream ifs;
ifs.open("demo.txt",ios::in);
if(!ifs.is_open){
cout<<"打开失败"<<endl;
return ;
}

读数据
1)
char buf[1023]={0};
while(ifs>>buf){
cout<<buf<<endl;
}
2)
char buf[1024]={0};
while(ifs.getline(buf,sizeof(buf))){
cout<<buf<<endl;
}
3)
string buf;
while(getline(ifs,buf)){cout<<buf<<endl;
}
4)

char c;
while((c=ifs.get())!=EOF){
cout<<buf<<endl;
}


关闭
ifs.close();
}

昨夜西风凋碧树,独上高楼,望尽天涯路 衣带渐宽终不悔,为伊消得人憔悴 众里寻他千百度。蓦然回首,那人却在,灯火阑珊处
原文地址:https://www.cnblogs.com/X404/p/14375292.html