ofstream是
C++标准库
中的一个输出
文件流类,用于向
文件 中 写入数据。其
使用方法如下:
1. 包含头
文件 c++ #include <fstream>
2. 创建
ofstream对象
c++ ofstream ofs;
3. 打开
文件 c++ ofs.open("filename.txt");
4.
写入数据
c++ ofs << "Hello, World!";
5. 关闭
文件 c++ ofs.close();
完整示例代码如下:
c++#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream
ofs;
ofs.open("output.txt");
if (!ofs) {
cerr << "Failed to open file!" << endl;
return 1;
}
ofs << "Hello, World!" << endl;
ofs << "This is a test." << endl;
ofs.close();
return 0;
}
以上代码会向名为 output.txt 的
文件 中 写入两行数据。注意,如果打开
文件失败,需要及时进行错误处理,避免因为
文件操作失败造成不必要的问题。
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.mushiming.com/mjsbk/7132.html