ifstream用于文件读取,继承自istream,支持>>和getline();ofstream用于文件写入,继承自ostream,使用
在C++中,文件操作主要通过头文件提供的类来实现。其中,ifstream和ofstream是最常用的两个类,分别用于文件的读取和写入。下面详细说明它们的区别及使用方法。
ifstream全称是 input file stream,用于从文件中读取数据。它继承自istream,支持使用>>操作符或getline()等方法读取内容。
常见用法:
示例代码:
#include#include #include 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,可以使用操作符将数据写入文件。
常见用途:
示例代码:
#include#include 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 的基本用法,就能完成大多数文本文件的读写任务。注意每次操作后检查文件状态,并及时关闭文件,这样更安全可靠。