目录
[一、 的核心功能](#一、 的核心功能)
[1. 文本文件写入(ofstream)](#1. 文本文件写入(ofstream))
[2. 文本文件读取(ifstream)](#2. 文本文件读取(ifstream))
[3. 二进制文件操作(fstream)](#3. 二进制文件操作(fstream))
一、<fstream> 的核心功能
<fstream>
是 C++ 标准库中处理文件输入输出的关键组件,提供以下核心功能:
文本/二进制文件读写、文件流状态管理、文件指针定位、多种文件打开模式控制
二、核心类及功能
类名 | 继承关系 | 功能描述 | 典型用途 |
---|---|---|---|
ofstream |
继承自 ostream |
输出文件流(写操作) | 创建/覆盖文件内容 |
ifstream |
继承自 istream |
输入文件流(读操作) | 读取文件内容 |
fstream |
继承自 iostream |
双向文件流(读写操作) | 同时读写文件 |
三、核心操作示例
1. 文本文件写入(ofstream)
cpp
#include <fstream>
int main() {
std::ofstream outFile("data.txt"); // 自动打开文件
if (outFile) { // 检查是否打开成功
outFile << "Line 1: 文本内容\n"; // 写入字符串
outFile << "Line 2: " << 42 << "\n"; // 写入混合数据
outFile << 3.14 << "\n"; // 写入浮点数
} else {
std::cerr << "文件打开失败!";
}
// 文件会在对象销毁时自动关闭
return 0;
}
生成文件内容:
cpp
Line 1: 文本内容
Line 2: 42
3.14
2. 文本文件读取(ifstream)
cpp
#include <fstream>
#include <iostream>
int main() {
std::ifstream inFile("data.txt");
if (inFile.is_open()) {
std::string line;
while (std::getline(inFile, line)) { // 逐行读取
std::cout << "读取内容: " << line << "\n";
}
} else {
std::cerr << "文件不存在!";
}
return 0;
}
输出结果:
cpp
读取内容: Line 1: 文本内容
读取内容: Line 2: 42
读取内容: 3.14
3. 二进制文件操作(fstream)
cpp
#include <fstream>
#include <iostream>
struct DataPacket {
int id;
double value;
char tag[20];
};
int main() {
// 写入二进制数据
DataPacket data{1001, 3.1415926, "binary"};
std::ofstream binOut("data.bin", std::ios::binary);
binOut.write(reinterpret_cast<char*>(&data), sizeof(data));
// 读取二进制数据
DataPacket loaded;
std::ifstream binIn("data.bin", std::ios::binary);
binIn.read(reinterpret_cast<char*>(&loaded), sizeof(loaded));
std::cout << "ID: " << loaded.id
<< "\nValue: " << loaded.value
<< "\nTag: " << loaded.tag;
return 0;
}
输出结果:
cpp
ID: 1001
Value: 3.14159
Tag: binary
四、文件打开模式
通过位或操作符 |
组合使用多种模式:
cpp
std::fstream file("data.txt",
std::ios::in | // 可读
std::ios::out | // 可写
std::ios::app | // 追加模式
std::ios::binary); // 二进制模式
模式标志 | 功能描述 |
---|---|
std::ios::in |
以读取模式打开文件 |
std::ios::out |
以写入模式打开文件 |
std::ios::app |
追加模式(不覆盖原有内容) |
std::ios::ate |
打开时定位到文件末尾 |
std::ios::trunc |
如果文件存在则清空内容 |
std::ios::binary |
以二进制模式操作文件 |
五、文件指针操作
cpp
std::fstream file("data.txt", std::ios::in | std::ios::out);
// 定位到第10字节处
file.seekg(10, std::ios::beg); // 输入指针(读取位置)
file.seekp(10, std::ios::beg); // 输出指针(写入位置)
// 获取当前指针位置
std::streampos readPos = file.tellg();
std::streampos writePos = file.tellp();
六、错误处理技巧
cpp
std::ifstream file("missing.txt");
// 检查文件状态
if (file.fail()) {
std::cerr << "错误代码: " << errno << std::endl;
}
// 重置错误状态
file.clear();
七、实际应用场景
-
配置文件读写 :使用文本模式处理
.ini
文件 -
数据持久化:用二进制格式保存游戏进度
-
日志系统:用追加模式记录程序运行日志
-
大数据处理:通过文件指针随机访问大型数据文件
通过以上示例和说明,可以全面掌握 <fstream>
库的核心用法。实际开发中需注意:
-
二进制操作时确保数据的内存布局一致
-
文件路径使用绝对路径或正确相对路径
-
及时处理文件流的状态异常