C++中fstream用于文件读写,包含ofstream、ifstream和fstream三个类,通过open()或构造函数打开文件,支持多种模式如ios::in、ios::out、ios::app、ios::binary等,可组合使用,操作时需检查is_open()、good()、fail()、bad()、eof()等状态,文本文件用操作,二进制文件用read()和write(),最后调用close()关闭文件。

在C++中,使用
fstream可以方便地进行文件的读写操作。它位于
头文件中,提供了三个主要类:
- ofstream:用于写入文件(output file stream)
- ifstream:用于读取文件(input file stream)
- fstream:既可以读也可以写
打开和关闭文件
要操作文件,首先要打开它。可以通过构造函数或
open()方法打开文件,操作完成后调用
close()关闭。 #include
#include iostream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (!outFile) {
cout
return 1;
}
outFile
outFile.close();
ifstream inFile("example.txt");
if (!inFile) {
cout
return 1;
}
string line;
while (getline(inFile, line)) {
cout
}
inFile.close();
return 0;
}
读写模式说明
fstream支持多种打开模式,通过参数指定:
- ios::out - 写入,文件不存在则创建
- ios::in - 读取
- ios::app - 追加写入,每次写都在末尾
- ios::trunc - 写入时清空原内容(默认)
- ios::binary - 以二进制方式操作
多个模式可以用
|组合:
立即学习“C++免费学习笔记(深入)”;
本文档主要介绍如何通过python对office excel进行读写操作,使用了xlrd、xlwt和xlutils模块。另外还演示了如何通过Tcl tcom包对excel操作。感兴趣的朋友可以过来看看
file.open("data.txt", ios::in | ios::out);
if (file.is_open()) {
file file.seekg(0); // 移动读取指针到开头
string s;
file >> s;
cout file.close();
}
检查文件状态
操作文件时应检查状态,避免出错。常用方法包括:
- is_open() - 文件是否成功打开
- good() - 所有状态正常
- fail() - 操作失败(如格式错误)
- eof() - 是否到达文件末尾
- bad() - 发生严重错误(如磁盘故障)
推荐在读写后判断是否成功:
ifstream in("test.txt");if (in.is_open()) {
string data;
if (!(in >> data)) {
cout }
in.close();
} else {
cout }
二进制文件读写
处理非文本数据时,使用
ios::binary模式,并配合
read()和
write()函数。 struct Person {
char name[20];
int age;
};
ofstream out("person.dat", ios::binary);
Person p = {"Tom", 25};
out.write(reinterpret_cast
out.close();
ifstream in("person.dat", ios::binary);
Person p2;
in.read(reinterpret_cast
cout
in.close();
基本上就这些。掌握好打开、读写、状态检查和关闭流程,就能安全高效地使用 fstream 操作文件。








