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
<fstream>
要操作文件,首先要打开它。可以通过构造函数或
open()
close()
int main() {
ofstream outFile("example.txt");
if (!outFile) {
cout << "无法打开文件用于写入!" << endl;
return 1;
}
outFile << "Hello, World!" << endl;
outFile.close();
ifstream inFile("example.txt");
if (!inFile) {
cout << "无法打开文件用于读取!" << endl;
return 1;
}
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
return 0;
}
fstream
多个模式可以用
|
立即学习“C++免费学习笔记(深入)”;
fstream file;操作文件时应检查状态,避免出错。常用方法包括:
推荐在读写后判断是否成功:
ifstream in("test.txt");处理非文本数据时,使用
ios::binary
read()
write()
ofstream out("person.dat", ios::binary);
Person p = {"Tom", 25};
out.write(reinterpret_cast<char*>(&p), sizeof(p));
out.close();
ifstream in("person.dat", ios::binary);
Person p2;
in.read(reinterpret_cast<char*>(&p2), sizeof(p2));
cout << p2.name << ", " << p2.age << endl;
in.close();
基本上就这些。掌握好打开、读写、状态检查和关闭流程,就能安全高效地使用 fstream 操作文件。
以上就是C++如何使用fstream读写文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号