C++中通过fstream类结合ios::binary标志实现二进制文件读写,使用write()和read()函数以字节形式存取数据,支持整数数组、结构体等原始内存布局数据的高效操作。

C++中读写二进制文件主要通过fstream类实现,使用ios::binary标志来指定以二进制模式操作文件。 与文本文件不同,二进制文件不会对数据进行格式转换,适合存储结构体、数组等原始字节数据。下面介绍基本操作方法并提供实用示例。
在C++中,使用ofstream写入二进制文件,ifstream读取二进制文件,fstream可同时支持读写。关键是要加上ios::binary参数。
例如:
使用write()函数将内存中的数据按字节写入文件。该函数接受指针和长度两个参数。
立即学习“C++免费学习笔记(深入)”;
示例:写入一个整数数组
#include <fstream>
#include <iostream>
int main() {
int data[] = {10, 20, 30, 40, 50};
std::ofstream file("numbers.bin", std::ios::binary);
if (file) {
file.write(reinterpret_cast<char*>(data), sizeof(data));
file.close();
std::cout << "数据写入完成。\n";
} else {
std::cerr << "无法打开文件!\n";
}
return 0;
}
使用read()函数从文件中读取原始字节到变量或数组中。同样需要指定目标地址和读取字节数。
示例:读取刚才保存的整数数组
#include <fstream>
#include <iostream>
int main() {
int data[5];
std::ifstream file("numbers.bin", std::ios::binary);
if (file) {
file.read(reinterpret_cast<char*>(data), sizeof(data));
if (file) {
std::cout << "读取的数据:";
for (int i = 0; i < 5; ++i)
std::cout << data[i] << " ";
std::cout << "\n";
} else {
std::cerr << "读取失败!可能文件不完整。\n";
}
file.close();
} else {
std::cerr << "无法打开文件!\n";
}
return 0;
}
二进制文件常用于保存结构体。只要注意内存对齐和跨平台兼容性,可以直接读写整个结构体。
示例:
#include <fstream>
#include <iostream>
#include <string>
struct Person {
char name[20];
int age;
};
int main() {
// 写入结构体
Person p = {"Alice", 25};
std::ofstream out("person.bin", std::ios::binary);
out.write(reinterpret_cast<char*>(&p), sizeof(p));
out.close();
// 读取结构体
Person p2;
std::ifstream in("person.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(&p2), sizeof(p2));
in.close();
std::cout << "姓名:" << p2.name << ", 年龄:" << p2.age << "\n";
return 0;
}
基本上就这些。掌握open()、write()、read()和正确的类型转换,就能高效操作二进制文件。注意检查文件是否成功打开和读写状态,避免因路径错误或权限问题导致程序异常。
以上就是c++++怎么读写二进制文件_c++二进制文件读写操作示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号