ifstream和ofstream区别与使用教程
作者:吹吹风会发光
时间:2025-09-18
浏览:1
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 写文件,注意检查是否成功打开,避免操作无效文件流。
作者最新文章
漫蛙网页版免费进入地址分享
2026-10-13 13:16
漫蛙manwa官方网站入口
2026-10-13 13:15
Typora怎么插入表格?Ctrl+T快速建表并调整行列
2026-10-05 17:59
2026年好用的思维导图软件推荐:高效实用排行榜
2026-09-30 13:14
寻简思维导图手机版设置在主题框中插入公式的方法
2026-09-30 13:03
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多































