C++中使用open创建文本文件并使用运算符<<写入文本

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 写入文件的方式相同。

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值