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)从文件中读取指定字节数到缓冲区。它不会跳过空白字符,也不会做任何格式解析。
立即学习“C++免费学习笔记(深入)”;
示例:读取一个整数数组
#include <fstream>
#include <iostream>
<p>int main() {
std::ifstream file("numbers.bin", std::ios::binary);
if (!file) {
std::cerr << "无法打开文件!" << std::endl;
return -1;
}</p><pre class='brush:php;toolbar:false;'>int arr[5];
file.read(reinterpret_cast<char*>(arr), sizeof(arr));
if (file.gcount() == sizeof(arr)) {
for (int i = 0; i < 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;
};
<p>Person p = {"Alice", 25};</p><p>std::ofstream file("person.bin", std::ios::binary);
if (file) {
file.write(reinterpret_cast<const char*>(&p), sizeof(p));
file.close();
}</p>关键点:直接写入结构体内存布局,适用于简单POD类型。若结构含指针或STL容器(如std::string),需序列化处理。
#pragma pack控制对齐file.good()、file.fail()等状态函数基本上就这些。掌握read和write的用法,配合正确的打开模式,就能高效处理C++中的二进制文件操作。不复杂但容易忽略细节。
以上就是C++如何读取二进制文件_C++ fstream read与write函数操作详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号