C++
提供了std::fstream
,旨在以独立于平台的方式访问文件。std::fstream
从std::ofstream
那里继承了写入文件的功能,并从std::ifstream
那里继承了读取文件的功能。换句话说,std::fstream
提供了读写文件的功能。
要使用std::fstream
类或其基类,需要包含头文件<fstream>
:
#include <fstream>
在C++
编程中,我们使用流插入运算符(<<
)向文件写入信息,就像使用该运算符输出信息到屏幕上一样。唯一 不同的是,在这里使用的是ofstream
或fstream
对象,而不是cout
对象。
同理,我们使用流提取运算符(>>
)从文件读取信息,就像使用该运算符从键盘输入信息一样。唯一不同的是,在这里您使用的是ifstream
或fstream
对象,而不是cin
对象。
1. 使用open( )和close( )打开和关闭文件
要使用fstream
、ofstream
或ifstream
类,需要使用方法open()
打开文件,open()
函数是fstream
、ifstream
和ofstream
对象的一个成员。
fstream myFile;myFile.open("HelloFile.txt",ios_base::in|ios_base::out|ios_base::trunc);if (myFile.is_open()) // check if open() succeeded{// do reading or writing heremyFile.close();}
open()
接受两个参数:
第一个是要打开的文件的路径和名称(如果没有提供路径,将假定为应用程序的当前目录设置);第二个是文件的打开模式。
可以把以上两种或两种以上的模式结合使用。例如,如果您想要以写入模式打开文件,并希望截断文件,以防文件已存在,那么您可以使用下面的语法:
ofstream outfile;outfile.open("file.dat", ios::out | ios::trunc );
类似地,您如果想要打开一个文件用于读写,可以使用下面的语法:
ifstream afile;afile.open("file.dat", ios::out | ios::in );
在上述代码中,指定了模式ios_base::trunc
(即便指定的文件存在,也重新创建它)、ios_base::in
(可读取文件)和ios_base::out
(可写入文件)。
注意到在上述代码中使用了is_open()
,它检测open()
是否成功。
注意:保存到文件时,必须使用close()
关闭文件流。close()
函数是fstream
、ifstream
和ofstream
对象的一个成员。
还有另一种打开文件流的方式,那就是使用构造函数:
fstream myFile("HelloFile.txt",ios_base::in|ios_base::out|ios_base::trunc);
如果只想打开文件进行写入,可使用如下代码:
ofstream myFile("HelloFile.txt", ios_base::out);
如果只想打开文件进行读取,可使用如下代码:
ifstream myFile("HelloFile.txt", ios_base::in);
注意:无论是使用构造函数还是成员方法open()
来打开文件流,都建议您在使用文件流对象前,使用open()
检查文件打开操作是否成功。
2. 使用open( )创建文本文件并使用运算符<<写入文本
有打开的文件流后,便可使用运算符<<
向其中写入文本。
#include <fstream>#include <iostream>using namespace std;int main(){ofstream myFile;myFile.open("HelloFile.txt", ios_base::out);if (myFile.is_open()){cout << "File open successful" << endl;myFile << "My first text file!" << endl;myFile << "Hello file!" << endl;cout << "Finished writing to file, will close now" << endl;myFile.close();}return 0;}
第 8 行以ios_base::out
模式(即只写模式)打开文件。第 10 行检查open( )
是否成功,然后使用插入运算符<<
写入该文件流。最后,第 18 行关闭文件流。
3. 使用open( )和运算符>>读取文本文件
要读取文件,可使用fstream
或ifstream
,并使用标志ios_base::in
打开它。
#include <fstream>#include <iostream>#include <string>using namespace std;int main(){ifstream myFile;myFile.open("HelloFile.txt", ios_base::in);if (myFile.is_open()){cout << "File open successful. It contains: " << endl;string fileContents;while (myFile.good()){getline (myFile, fileContents);cout << fileContents << endl;}cout << "Finished reading file, will close now" << endl;myFile.close();}elsecout << "open() failed: check if file is in right folder" << endl;return 0;}
请注意,这里没有使用提取运算符>>
将文件内容直接读取到第 18 行使用cout
显示的string
,而是使用getline()
从文件流中读取输入。