C++中通过fstream库实现文件读写,包含ifstream、ofstream和fstream三个类,分别用于输入、输出及双向操作,需包含头文件<fstream>。1. 使用open()函数或构造函数打开文件,支持多种模式如ios::in、ios::out、app、binary等。2. 文本文件可使用<<、>>和getline()进行格式化读写,注意空白处理差异。3. 二进制文件需以ios::binary模式打开,用read()和write()直接操作字节,常用于结构体存储。4. 操作中应检查good()、eof()、fail()、bad()等状态标志,确保流正常。5. 可通过seekg()、seekp()定位文件指针,tellg()、tellp()获取当前位置。正确使用这些功能可实现数据持久化、日志记录等任务。

在C++中,文件读写是程序与外部数据交互的重要方式。通过标准库中的 fstream(file stream)类,我们可以方便地对文件进行读取和写入操作。它属于C++输入输出流体系的一部分,包含在头文件 fstream 中。
C++ 提供了三种主要的文件流类,它们都定义在 #include <fstream> 中:
这些类继承自 iostream 体系,支持使用 << 和 >> 操作符进行格式化读写,也支持 getline、read、write 等更高级的操作。
使用文件流的第一步是打开文件。可以通过构造函数或 open() 成员函数实现。
立即学习“C++免费学习笔记(深入)”;
#include <fstream>
#include <iostream>
using namespace std;
<p>int main() {
ofstream outFile;
outFile.open("data.txt"); // 打开文件用于写入</p><pre class='brush:php;toolbar:false;'>if (!outFile.is_open()) {
cout << "无法打开文件!" << endl;
return -1;
}
outFile << "Hello, World!" << endl;
outFile.close(); // 显式关闭文件
return 0;}
open() 函数原型为:
void open(const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out);
常用打开模式包括:
例如,以追加方式写入文件:
ofstream file("log.txt", ios::app);
file << "新日志条目" << endl;
file.close();
对于文本文件,可以使用流操作符或 getline 进行读写。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
<p>int main() {
// 写入文本文件
ofstream out("example.txt");
out << "第一行\n第二行\n第三行";
out.close();</p><pre class='brush:php;toolbar:false;'>// 读取文本文件
ifstream in("example.txt");
string line;
while (getline(in, line)) {
cout << line << endl;
}
in.close();
return 0;}
注意:>> 操作符会跳过空白字符并按字段读取,而 getline() 可以读取整行,包括中间的空格,遇到换行符停止(但不保存换行符)。
处理非文本数据(如结构体、图像、音频)时,应使用二进制模式。
struct Student {
char name[20];
int age;
};
<p>int main() {
// 写入二进制文件
ofstream out("student.dat", ios::binary);
Student s1 = {"Alice", 20};
out.write(reinterpret_cast<char*>(&s1), sizeof(s1));
out.close();</p><pre class='brush:php;toolbar:false;'>// 读取二进制文件
ifstream in("student.dat", ios::binary);
Student s2;
in.read(reinterpret_cast<char*>(&s2), sizeof(s2));
in.close();
cout << "姓名:" << s2.name << ", 年龄:" << s2.age << endl;
return 0;}
关键点:
读写过程中应检查文件状态,防止出错。
常用状态标志:
还可以使用 clear() 清除错误状态。
定位文件指针:
ifstream file("data.txt", ios::binary);
file.seekg(10, ios::beg); // 从开头偏移10字节
file.seekg(-5, ios::end); // 从结尾前移5字节
streampos pos = file.tellg(); // 获取当前位置
基本上就这些。掌握 fstream 的基本用法后,你可以灵活处理配置文件、日志记录、数据持久化等任务。重点在于理解打开模式、区分文本与二进制操作,并养成检查状态的好习惯。不复杂但容易忽略细节。
以上就是C++文件读写fstream操作教程_C++输入输出流高级用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号