使用ofstream写入文件,需包含fstream头文件,创建输出流对象并打开文件,通过<<操作符写入内容,最后关闭文件。示例:ofstream outFile("example.txt"); outFile << "Hello"; outFile.close();

在C++中向文件写入内容,主要通过标准库中的 fstream 头文件提供的类来实现。常用的类包括 ofstream(输出文件流),用于将数据写入文件。下面详细介绍几种常见的文件写入方法。
1. 使用 ofstream 写入文本文件
ofstream 是专门用于写入文件的类。只要包含 fstream 头文件,就可以创建 ofstream 对象并打开文件进行写入。
基本步骤如下:
- 包含头文件:#include <fstream>
- 创建 ofstream 对象
- 打开目标文件
- 使用输出操作符 << 写入内容
- 关闭文件(可选,析构函数会自动关闭)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, this is a test.\n";
outFile << "Second line of text.\n";
outFile.close();
cout << "内容已写入文件。\n";
} else {
cout << "无法打开文件!\n";
}
return 0;
}
2. 文件打开模式说明
ofstream 默认以覆盖方式写入(从头开始写,原内容会被清除)。可以通过指定模式来改变行为。
立即学习“C++免费学习笔记(深入)”;
常用模式:
- ios::out:默认写入模式
- ios::app:追加模式,新内容添加到文件末尾
- ios::trunc:清空原文件内容(默认行为)
ofstream outFile("example.txt", ios::app);
if (outFile.is_open()) {
outFile << "这条内容会被追加到文件末尾。\n";
outFile.close();
}
3. 写入二进制数据
如果要写入非文本内容(如结构体、数组等),需要以二进制模式打开文件,并使用 write() 函数。
示例:写入整数数组
#include <fstream>
using namespace std;
int main() {
int data[] = {10, 20, 30, 40, 50};
ofstream binFile("data.bin", ios::binary);
if (binFile.is_open()) {
binFile.write(reinterpret_cast<const char*>(data), sizeof(data));
binFile.close();
cout << "二进制数据写入完成。\n";
}
return 0;
}
4. 错误处理建议
写入文件时,应始终检查文件是否成功打开,避免因路径错误或权限问题导致程序异常。
- 使用 is_open() 判断文件状态
- 写入后可调用 fail() 或 bad() 检查操作是否成功











