使用fstream操作二进制文件需指定std::ios::binary标志,通过write()和read()函数以char*指针形式读写原始字节,适用于POD类型,注意跨平台对齐和数据兼容性问题。

在C++中,使用fstream读写二进制文件是处理非文本数据的常见需求,比如图像、音频、序列化对象等。与文本模式不同,二进制模式能确保数据原样读写,不会被系统转换(如换行符替换)。下面详细介绍如何正确使用fstream进行二进制文件操作。
打开二进制文件的方式
使用std::fstream、std::ifstream或std::ofstream时,需指定std::ios::binary标志,以确保以二进制模式打开文件。
示例代码:
std::ofstream outFile("data.bin", std::ios::out | std::ios::binary);
std::ifstream inFile("data.bin", std::ios::in | std::ios::binary);
std::fstream file("data.bin", std::ios::in | std::ios::out | std::ios::binary);
如果不加std::ios::binary,在Windows系统上可能会出现数据被意外修改的情况。
立即学习“C++免费学习笔记(深入)”;
写入二进制数据
使用write()成员函数将内存中的原始字节写入文件。该函数接受一个const char*指针和要写入的字节数。
例如,保存一个整数数组:
int data[] = {10, 20, 30, 40};
outFile.write(reinterpret_cast
// 或者更清晰:
outFile.write(reinterpret_cast
注意:必须使用reinterpret_cast将任意类型指针转为char*,因为write()只接受字符指针。
读取二进制数据
使用read()函数从文件中读取指定数量的字节到内存缓冲区。
继续上面的例子:
int readData[4];
inFile.read(reinterpret_cast
读取后建议检查是否成功:
if (inFile) {
// 读取成功
} else {
// 可能读到了文件末尾或出错
}
也可以用gcount()获取实际读取的字节数。
处理复杂数据结构
对于结构体或类对象,可以直接读写整个对象的内存映像,但要注意以下几点:
- 结构体不能包含指针或动态分配的数据(如std::string)
- 可能存在内存对齐差异,跨平台时需谨慎
- 推荐对简单POD(Plain Old Data)类型使用此方法
示例:
struct Point {
float x, y;
};
Point p{1.5f, 2.5f};
outFile.write(reinterpret_cast
Point p2;
inFile.read(reinterpret_cast
基本上就这些。只要记住用binary模式、正确使用read/write、注意类型转换和数据兼容性,就能安全地操作二进制文件。








