C ++ read and write files, fstream

Reading and writing files

  • There are many ways to read and write files. Here is a brief introduction to fstream. It provides a stream to manipulate files. It feels the same as cin / cout and is very easy to get started.

head File:

#include<fstream>

Open the file input stream:

ifstream in("test.txt");
//如果打开失败将返回0
if(!in){
	//打开失败
}

If you open the result, it is the same usage as cin, let's look at a program to find the name

string name;
while(in>>name){
	if(name=="target"){
		cout<<"find "<<name<<endl;
		break;
	}
}

Open the file output stream:

//默认打开方式是覆盖,我们可以指定为追加(append),通过第二个参数
ofstream out("test.txt",ios_base::app);
if(!out){
	//打开失败
}

If the opening is successful, the same usage as cout, no longer demonstrate

Open the file input and output stream:

If you want to read and write files at the same time, open the file input and output stream

fstream io("test.txt",ios_base::in|ios_base::app);
if(!io){
	//打开失败
}
else{
	iofile.seekg(0);
	//文件io流中有输入和输出两个指针,seekp是输出指针,seekg是输入指针
	//这里将输入定位到了文件头部
}

Close the stream:

Just call the .close () function, for example

in.close();

mode:

Common open mode

The following constants are also defined:
Constant Explanation
app seek to the end of stream before each write
binary open in binary mode
in open for reading
out open for writing
trunc discard the contents of the stream when opening
ate seek to the end of stream immediately after open

Guess you like

Origin www.cnblogs.com/qishihaohaoshuo/p/12747666.html