1. C++文件操作与序列化核心概念解析
在C++开发中,文件操作和序列化是数据处理的基础能力。fstream作为C++标准库中的文件流类,提供了完善的读写接口。我见过不少开发者在使用时遇到文件权限、编码格式等问题,其实只要掌握几个关键点就能避免90%的常见错误。
序列化本质上是一种对象持久化机制。当我们需要将游戏存档、配置文件或网络传输数据转换为二进制或文本格式时,序列化就派上用场了。反序列化则是逆向过程,把存储的数据重新构建为内存对象。这个过程需要考虑字节序、内存对齐等底层细节,这也是为什么很多跨平台项目会专门设计序列化协议。
重要提示:Windows和Linux系统下的文件路径写法不同,建议使用filesystem库中的path类进行跨平台处理
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 文件操作实战:从基础到进阶
2.1 基本文件读写操作
先看一个最基础的文件写入示例:
cpp复制#include <fstream>
#include <string>
void basicWrite() {
std::ofstream outFile("data.txt");
if(outFile.is_open()) {
outFile << "Hello File!" << std::endl;
outFile << 42 << std::endl; // 写入整数
outFile.close();
}
}
读取时需要注意错误处理:
cpp复制void basicRead() {
std::ifstream inFile("data.txt");
std::string line;
if(!inFile) {
std::cerr << "文件打开失败" << std::endl;
return;
}
while(getline(inFile, line)) {
std::cout << "读取到: " << line << std::endl;
}
inFile.close();
}
2.2 二进制模式与文本模式区别
二进制模式不会进行任何转换,适合保存结构体等数据:
cpp复制struct Person {
char name[20];
int age;
};
void binaryWrite() {
Person p = {"张三", 25};
std::ofstream outFile("person.dat", std::ios::binary);
outFile.write(reinterpret_cast<char*>(&p), sizeof(Person));
outFile.close();
}
读取时需要注意内存对齐问题:
cpp复制void binaryRead() {
Person p;
std::ifstream inFile("person.dat", std::ios::binary);
if(inFile.read(reinterpret_cast<char*>(&p), sizeof(Person))) {
std::cout << "姓名: " << p.name
<< " 年龄: " << p.age << std::endl;
}
inFile.close();
}
2.3 文件指针操作技巧
随机访问文件需要使用seekg和seekp:
cpp复制void randomAccess() {
std::fstream file("data.bin",
std::ios::in | std::ios::out | std::ios::binary);
// 写入10个整数
