使用fstream类并指定std::ios::binary模式可实现C++中二进制文件的读写,示例中通过write()和read()函数以字节形式存取整型数组,确保数据完整性和内存安全。

在C++中读写二进制文件,关键在于使用标准库中的fstream类,并正确设置文件打开模式为二进制。与文本文件不同,二进制文件以原始字节形式存储数据,不会对换行符等字符做转换,适合保存结构体、数组或任意内存块。
打开二进制文件进行读写
使用std::ifstream读取二进制文件,std::ofstream写入二进制文件,std::fstream可同时支持读写。必须在打开文件时指定std::ios::binary标志,否则在Windows平台可能出现数据误读。
#include#include int main() { std::ofstream file("data.bin", std::ios::binary); if (!file) { std::cerr << "无法打开文件!" << std::endl; return 1; } int numbers[] = {10, 20, 30, 40, 50}; file.write(reinterpret_cast (numbers), sizeof(numbers)); file.close(); return 0; }
从二进制文件读取数据
读取时使用read()函数,将数据读入预分配的缓冲区。注意确保目标内存大小足够,避免越界。
std::ifstream file("data.bin", std::ios::binary);
if (!file) {
std::cerr << "无法打开文件!" << std::endl;
return 1;
}
int numbers[5];
file.read(reinterpret_cast(numbers), sizeof(numbers));
if (file.gcount() != sizeof(numbers)) {
std::cerr << "读取数据不完整!" << std::endl;
} else {
for (int i = 0; i < 5; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
}
file.close();
读写结构体或类对象
直接写入和读取结构体是二进制I/O的常见用法。但需注意结构体内存对齐可能导致填充字节,跨平台使用时应谨慎。
立即学习“C++免费学习笔记(深入)”;
示例:保存和恢复结构体
struct Person {
int age;
double height;
char name[32];
};
// 写入
Person p{25, 1.78, "Alice"};
std::ofstream out("person.bin", std::ios::binary);
out.write(reinterpret_cast(&p), sizeof(p));
out.close();
// 读取
Person p2;
std::ifstream in("person.bin", std::ios::binary);
in.read(reinterpret_cast(&p2), sizeof(p2));
in.close();
注意事项:
- 始终检查文件是否成功打开(
if (!file)) - 使用
gcount()确认实际读取字节数 - 结构体包含指针时不能直接序列化,需手动处理
- 跨平台传输时考虑字节序(endianness)问题
- 避免使用
sizeof(std::string)等非POD类型直接写入
read和write配合reinterpret_cast的用法,再注意数据类型的兼容性,C++中操作二进制文件并不复杂但容易忽略细节。











