C++中使用open创建文本文件并使用运算符<<写入文本
C++提供了 std::fstream,旨在以独立于平台的方式访问文件。 std::fstream 从 std::ofstream 那里继承了写入文件的功能,并从 std::ifstream 那里继承了读取文件的功能。 要使用 fstream、 ofstream 或 ifstream 类,需要使用方法 open()打开文件。有打开的文件流后,便可使用运算符<<向其中写入文本,如程序清单 27.8 所示。
程序清单 27.8 使用 ofstream 新建一个文本文件并向其中写入文本
0: #include<fstream>
1: #include<iostream>
2: using namespace std;
3:
4: int main()
5: {
6: ofstream myFile;
7: myFile.open("HelloFile.txt", ios_base::out);
8:
9: if (myFile.is_open())
10: {
11: cout << "File open successful" << endl;
12:
13: myFile << "My first text file!" << endl;
14: myFile << "Hello file!";
15:
16: cout << "Finished writing to file, will close now" << endl;
17: myFile.close();
18: }
19:
20: return 0;
21: }
输出:
File open successful
Finished writing to file, will close now
HelloFile.txt 文件的内容如下:
My first text file!
Hello file!
分析:
第 7 行以 ios_base::out 模式(即只写模式)打开文件。第 9 行检查 open( )是否成功,然后使用插
入运算符<<写入该文件流,如第 13 和 14 行所示。最后,第 17 行关闭文件流。
程序清单 27.8 表明, 写入文件的方式与使用 cout 写入到标准输出(控制台)的方式相同。
这表明, C++流让您能够以类似的方式处理不同的设备:使用 cout 将文本显示到屏幕的
方式与使用 ofstream 写入文件的方式相同。