C++中通过std::fstream结合std::ios::binary标志实现二进制文件读写,使用read()和write()函数直接操作内存数据,需注意跨平台字节序、结构体对齐及错误检查,确保数据完整性。
在C++中读取和写入二进制文件,主要通过std::fstream类结合read()与write()函数实现。与文本文件不同,二进制操作要求精确控制数据的输入输出,避免格式转换。下面详细介绍如何使用这些功能。
使用std::fstream时,必须在打开文件时指定std::ios::binary标志,否则系统可能按文本模式处理换行符(如Windows下将\r\n转换为\n),导致数据错误。
常见打开方式包括:
std::ifstream file("data.bin", std::ios::binary); —— 只读模式打开二进制文件std::ofstream file("data.bin", std::ios::binary); —— 只写模式创建或覆盖文件std::fstream file("data.bin", std::ios::in | std::ios::out | std::ios::binary); —— 可读可写read(char* buffer, std::streamsize count)从文件中读取指定字节数到缓冲区。它不会跳过空白字符,也不会做任何格式解析。
示例:读取一个整数数组
#include#include int main() { std::ifstream file("numbers.bin", std::ios::binary); if (!file) { std::cerr << "无法打开文件!" << std::endl; return -1; }
int arr[5]; file.read(reinterpret_castzuojiankuohaophpcnchar*youjiankuohaophpcn(arr), sizeof(arr)); if (file.gcount() == sizeof(arr)) { for (int i = 0; i zuojiankuohaophpcn 5; ++i) std::cout << arr[i] << " "; } else { std::cerr << "读取数据不完整!" << std::endl; } file.close(); return 0;
}
注意:用gcount()检查实际读取的字节数,判断是否读完预期内容。
write(const char* buffer, std::streamsize count)将内存中的原始字节写入文件。
示例:保存一个结构体到文件
struct Person {
char name[20];
int age;
};
Person p = {"Alice", 25};
std::ofstream file("person.bin", std::ios::binary);
if (file) {
file.write(reinterpret_cast(&p), sizeof(p));
file.close();
}
关键点:直接写入结构体内存布局,适用于简单POD类型。若结构含指针或STL容器(如std::string),需序列化处理。
#pragma pack控制对齐file.good()、file.fail()等状态函数基本上就这些。掌握read和write的用法,配合正确的打开模式,就能高效处理C++中的二进制文件操作。不复杂但容易忽略细节。