C++官网参考链接:https://cplusplus.com/doc/tutorial/files/
输入/输出文件
C++提供了以下类来执行向文件输出和从文件中输入字符:
*ofstream(ofstream
):写入文件中的流类
*ifstream(ifstream
):从文件中读取的流类
*fstream(fstream
):从文件中读取和写入到文件中的流类。
这些类直接或间接地派生自类istream和ostream。我们已经使用过这些类类型的对象:cin是istream类的对象,cout是ostream类的对象。因此,我们已经使用了与文件流相关的类。事实上,我们可以像使用cin和cout一样使用文件流,唯一不同的是我们必须将这些流与物理文件关联起来。让我们看一个例子:
// basic file operations
#include
#include
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
这段代码创建了一个名为example.txt的文件,并以与cout相同的方式在其中插入一句话,但使用的是文件流myfile。
但让我们一步一步来:
打开一个文件
对这些类的对象执行的第一个操作通常是将其关联到一个真实文件。这个过程被称为打开文件。一个打开的文件在程序中由一个流表示(即,这些类中的一个对象;在前面的例子中,这是myfile),对这个流对象执行的任何输入或输出操作都将应用到与它关联的物理文件。
为了打开带有流对象的文件,我们使用它的成员函数open:
open (filename, mode);
其中filename是表示要打开的文件名的字符串,mode是一个可选形参,由以下标志的组合组成:
ios::in |
Open for input operations. |
ios::out |
Open for output operations. |
ios::binary |
Open in binary mode. |
ios::ate |
Set the initial position at the end of the file. (设置文件结束处的初始位置。如果未设置此标志,则初始位置为文件的开始。) |
ios::app |
All output operations are performed at the end of the file, appending the content to the current content of the file. (所有输出操作都在文件结束处执行,将内容追加到文件的当前内容。) |
ios::trunc |