C++文件操作

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

操作文件的三大类:
1、ofstream:写操作
2、ifstream:读操作
3、fstream:读写操作

打开方式 作用
ios::in 为读文件而打开文件,
ios::out 为写文件而打开文件,若没有则创建一个文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在先删除,再创建
ios::binary 二进制方式

1.文本方式读文件

#include<iostream>
using namespace std;

#include<fstream>//文件操作头文件
 
//文本文件:以ASC||码形式储存 (可以看懂的文件) 

//操作文件三大类:1.ofstream:写操作  2.ifstream:读操作   3.fstream;读写操作 
void test01()
{
	ofstream ofs;//创建流对象(写文件) 
	
	ofs.open("text.txt",ios::out);//打开文件。ofs.open("文件路径",打开方式)
	
	ofs<<"姓名:杜雯菲"<<endl; //写内容 ,利用<<写数据 
	
	ofs<<"年龄:188"<<endl; //写内容 
	
	ofs<<"性别:不详"<<endl; //写内容 
	
	ofs.close(); //操作完成后一定要关闭文件 
}
int main()
{
	
	test01();
	return 0;
 } 

测试结果
在这里插入图片描述

2.文本方式读文件

#include<iostream>
using namespace std;
#include<string> 
#include<fstream>//文件操作头文件

void test01()
{
	//创建流对象(读文件) 
	ifstream ifs;
	ifs.open("text.txt",ios::in);
	
	if(!ifs.is_open())
	{
		cout<<"打开失败"; 
		return ;
	}
	//方法一.读数据
	cout<<"方法一: "<<endl; 
	char buf01[1024]={0};
	while(ifs>>buf01)
	{
		cout<<buf01<<endl;
	 } 
	 //方法二.读数据
	 cout<<"方法二: "<<endl;
	 ifstream ifsl("text.txt",ios::in); 
	 char buf02[1024]={0};
	 while(ifsl.getline(buf02,sizeof(buf02)))
	 {
	 	cout<<buf02<<endl;
	 }
	 //方法三.读数据
	 cout<<"方法三:"<<endl; 
	 ifstream ifsp("text.txt",ios::in); 
	 string buf03;
	 while(getline(ifsp,buf03))
	 {
	 	cout<<buf03<<endl;
	 }
	  //方法四.读数据
	  cout<<"方法四: "<<endl;
	  ifstream ifsq("text.txt",ios::in); 
	char c;
	while((c=ifsq.get())!=EOF)
	{
		cout<<c;
	 } 
	  
	 ifs.close();
}
int main()
{
	test01();
 } 

测试结果
在这里插入图片描述

3.二进制方式写文件

#include<iostream>
using namespace std;
#include<string> 
#include<fstream>//文件操作头文件

//二进制方式操作写二进制文件:ios::binary 
class person
{
public:
	char Name[100];
	int Age;
};
//注意:文件打开方式可以配合使用,利用|操作符
void test01()
{
	ofstream ofs;
	ofs.open("person.txt",ios::out|ios::binary);
	
	person p={"杜雯菲",88};
	
	ofs.write((const char*)&p,sizeof(person));
	
	ofs.close();
	
}
int main()
{
	test01();
}

测试结果
在这里插入图片描述

4.二进制方式读文件

#include<iostream>
using namespace std;
#include<string> 
#include<fstream>//文件操作头文件

//二进制方式操作读二进制文件:ios::binary 
class person
{
public:
	char Name[100];
	int Age;
};
void test01()
{
	ifstream ifs;
	ifs.open("person.txt",ios::out|ios::binary);
	if(!ifs.is_open())
	{
		cout<<"打开文件失败";
		return; 
	 } 
	person q;
	ifs.read((char*)&q,sizeof(person));
	cout<<"年龄:"<<q.Age<<"  姓名:"<<q.Name<<endl;
	
	ifs.close();
	
}
int main()
{
	test01();
}

测试结果
在这里插入图片描述
在这里插入图片描述

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>