ifstream用于文件读取,继承自istream,支持>>和getline();ofstream用于文件写入,继承自ostream,使用<<操作符;两者默认分别以只读和覆盖写入方式打开文件,可通过ios::app等模式控制行为。

在C++中,文件操作主要通过<fstream>头文件提供的类来实现。其中,ifstream和ofstream是最常用的两个类,分别用于文件的读取和写入。下面详细说明它们的区别及使用方法。
ifstream全称是 input file stream,用于从文件中读取数据。它继承自istream,支持使用>>操作符或getline()等方法读取内容。
常见用法:
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream file("data.txt");
if (!file.is_open()) {
std::cout << "无法打开文件!" << std::endl;
return 1;
}
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
return 0;
}
ofstream全称是 output file stream,用于向文件写入数据。它继承自ostream,可以使用<<操作符将数据写入文件。
常见用途:
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("output.txt");
if (!file.is_open()) {
std::cout << "无法创建文件!" << std::endl;
return 1;
}
file << "Hello, World!" << std::endl;
file << "写入整数:" << 123 << std::endl;
file.close();
return 0;
}
>> 或 getline();ofstream 使用 << 写入数据。两者都可以通过指定模式参数来改变行为,例如:
std::ios::app:追加模式,适用于 ofstream,写入内容添加到文件末尾。std::ios::in:ifstream 的默认模式,只读。std::ios::out:ofstream 的默认模式,写入(覆盖)。std::ios::trunc:写入时清空原文件(默认行为)。追加写入示例:
std::ofstream file("log.txt", std::ios::app);
if (file.is_open()) {
file << "新增日志条目\n";
file.close();
}
基本上就这些。掌握 ifstream 和 ofstream 的基本用法,就能完成大多数文本文件的读写任务。注意每次操作后检查文件状态,并及时关闭文件,这样更安全可靠。
以上就是C++ ifstream和ofstream区别_C++文件输入流与输出流操作详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号