您的位置:首页 >C++ fstream文件读写教程
发布于2025-12-02 阅读(0)
扫一扫,手机访问
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;也可以在构造时直接打开文件:
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 << "姓名: 张三" << std::endl;对于二进制写入,使用 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 处理大多数文件任务。注意路径正确、及时关闭文件、避免内存泄漏。对于复杂数据结构,建议配合序列化方法使用。不复杂但容易忽略细节。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9