Linux---文件操作

在C++中,引入了流的概念。C++中流是指信息从输入设备到输出设备的过程。在C++中有三种流,标准IO流、文件IO流、字符串IO流。

C++文件流

在C++中派生出4个类,分别是输入流istream、输出流ostream、文件流基类fstreambase、字符串流基类strstreambase。在C++中如果需要对文件进行处理,必须包含#include<fstream>头文件。

描述信息
ifstream 表述输入文件流,用于从文件中读取数据
ofstream 表述输出文件流,用于创建文件并向文件中写入数据
fstream 表述文件流,具有写数据与读数据的两种功能

打开文件

void open(const char* filename,openmode mode)

  • filename:文件名
  • mode:文件打开模式
文件打开模式 描述
app 追加
ate 打开文件指定文件末尾
in 输出,打开文件用于读数据
out 输入,打开文件用于些数据

如果我们打开文件需要两种或者两种以上的方式,可以使用下面这种方式。

ofstream outfile;
outfile.open("text.txt",ios::out | ios::app); //以打开、追加的模式进行打开

在打开文件后,我们需要判断文件是否顺利被打开只需要调用is_open函数即可。

关闭文件

void close()

读写数据

在C语言中我们使用write函数进行文件的写入,但是在C++中增加了文件流,因此我们操作文件就非常简单,我们可以使用流运算符进行操作。

  • << 插入流运算符,用于向文件中写入数据。
  • 读取流运算符,用于读取文件中的数据。

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main()
{
    
    
	ofstream outfile;
	outfile.open("text.txt");
	if(outfile.is_open())
	{
    
    
		cout<<"outfile open file success"<<endl;
		string str;
		cout<<"please enter the content: ";
		cin>>str;
		outfile<<str;
		cout<<"write content success"<<endl;
		outfile.close();
	}
	else
	{
    
    
		cout<<"outfile open file error"<<endl;
		return -1;
	}
	
	ifstream infile;
	infile.open("text.txt");
	if(infile.is_open())
	{
    
    
		infile>>str;
		cout<<"Read content: ";
		cout<<str<<endl;
		infile.close();
	}
	else
	{
    
    
		cout<<"infile open file error"<<endl;
		return -1;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42708024/article/details/109592270