fstream是C++中用于文件读写的类,需包含<fstream>头文件,支持文本和二进制文件的输入输出,结合了ifstream和ofstream功能,通过open函数指定in、out、app等模式打开文件,可用<<或write()写入,用>>或getline()读取。

在C++中,fstream 是用于文件读写操作的核心类,它位于 fstream 头文件中。通过 fstream 可以方便地对文本和二进制文件进行输入输出操作。它继承自 iostream,并结合了 ifstream(输入)和 ofstream(输出)的功能。
使用 fstream 前必须包含对应的头文件:
#include <fstream>然后声明一个 fstream 对象:
std::fstream file;也可以在构造时直接打开文件:
立即学习“C++免费学习笔记(深入)”;
std::fstream file("example.txt", std::ios::in | std::ios::out);打开文件时可以指定多种模式,用 std::ios 枚举值控制:
例如,以读写方式打开文件,若不存在则创建:
file.open("data.txt", std::ios::in | std::ios::out | std::ios::app);如果文件不存在且未指定 out 或 app 模式,open 会失败。
使用 << 操作符或 write() 函数写入数据。
file file对于二进制写入,使用 write():
int value = 100;使用 >> 操作符读取格式化数据:
std::string name;逐行读取可用 std::getline:
std::string line;二进制读取使用 read():
int data;操作前后应检查文件是否成功打开或读写正常:
if (!file.is_open()) {if (file.fail()) {
std::cerr << "读写失败!" << std::endl;
}
使用完成后务必关闭文件:
file.close();int main() {
fstream file("test.txt", ios::out);
if (file.is_open()) {
file << "Hello, C++!" << endl;
file << "Age: 25" << endl;
file.close();
}
file.open("test.txt", ios::in);
if (file.is_open()) {
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
return 0;
}
这个例子先写入两行文本,再读取并打印出来。
基本上就这些。掌握 open、读写操作、模式选择和状态检查,就能灵活使用 fstream 处理大多数文件任务。注意路径正确、及时关闭文件、避免内存泄漏。对于复杂数据结构,建议配合序列化方法使用。不复杂但容易忽略细节。
以上就是c++++中如何使用fstream读写文件_C++ fstream文件流读写操作指南的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号