ifstream和ofstream区别与使用教程
作者:吹吹风会发光
时间:2025-09-18
浏览:0
ifstream用于读取文件,是istream的派生类,通过>>或getline读取数据;2.ofstream用于写入文件,是ostream的派生类,通过<<写入数据。两者均在fstream头文件中定义。
ifstream用于读取文件,是istream的派生类,通过>>或getline读取数据;2. ofstream用于写入文件,是ostream的派生类,通过<<写入数据。两者均在fstream头文件中定义。

在C++中,ifstream 和 ofstream 是用于文件操作的两个常用类,它们都定义在 fstream 头文件中。这两个类分别用于读取和写入文件,是基于 istream 和 ostream 的派生类。
1. ifstream:用于读取文件
ifstream 全称是 input file stream,表示“输入文件流”,用来从文件中读取数据。
常见用法:
- 包含头文件:#include
- 创建 ifstream 对象并打开文件
- 使用 >> 操作符或 getline() 读取内容
- 关闭文件(可选,析构函数会自动关闭)
示例代码:
#include
#include
#include
using namespace std;
int main() {
ifstream file("data.txt"); // 打开文件用于读取
if (!file.is_open()) {
cout << "无法打开文件!" << endl;
return 1;
}
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close(); // 可省略
return 0;
}
2. ofstream:用于写入文件
ofstream 全称是 output file stream,表示“输出文件流”,用来向文件写入数据。
常见用法:
- 包含头文件:#include
- 创建 ofstream 对象并打开文件
- 使用 << 操作符写入数据
- 关闭文件(建议显式关闭)
示例代码:
#include
#include
using namespace std;
int main() {
ofstream file("output.txt"); // 创建或清空文件用于写入
if (!file.is_open()) {
cout << "无法创建文件!" << endl;
return 1;
}
file << "Hello, World!" << endl;
file << "这是一行文本。" << endl;
file.close(); // 建议显式关闭
return 0;
}
3. 主要区别总结
| 特性 | ifstream | ofstream |
|---|---|---|
| 用途 | 从文件读取数据 | 向文件写入数据 |
| 对应操作 | 输入(>> 或 getline) | 输出(<<) |
| 打开模式 | 默认只读 | 默认覆盖写入(清空原内容) |
| 文件不存在 | 打开失败 | 尝试创建(通常成功) |
| 头文件 | 都需 #include |
|
4. 扩展:fstream(读写兼备)
如果需要同时读写文件,可以使用 fstream 类,并指定打开模式。
例如:
fstream file("data.txt", ios::in | ios::out); // 可读可写
基本上就这些。根据需求选择 ifstream 读文件、ofstream 写文件,注意检查是否成功打开,避免操作无效文件流。
作者最新文章
iphone蓝牙连接ipad有什么用及连接方法教程
2026-09-21 17:28
PDF怎么取消密码保护?4种解锁方法整理
2026-09-08 18:23
三星 Galaxy Z Fold8 内屏边角支撑偏软?实测与官方回应
2026-09-08 16:39
手机Excel表格制作教程:小屏幕高效录入与格式调整指南
2026-09-04 09:27
PDF文档按页转换成图片怎么做?在线转换步骤整理
2026-09-03 11:06
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































