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

在C++中读写二进制文件,关键在于使用标准库中的fstream类,并正确设置文件打开模式为二进制。与文本文件不同,二进制文件以原始字节形式存储数据,不会对换行符等字符做转换,适合保存结构体、数组或任意内存块。
使用std::ifstream读取二进制文件,std::ofstream写入二进制文件,std::fstream可同时支持读写。必须在打开文件时指定std::ios::binary标志,否则在Windows平台可能出现数据误读。
#include <fstream>
#include <iostream>
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<const char*>(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<char*>(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<const 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();
if (!file))gcount()确认实际读取字节数sizeof(std::string)等非POD类型直接写入read和write配合reinterpret_cast的用法,再注意数据类型的兼容性,C++中操作二进制文件并不复杂但容易忽略细节。以上就是c++++ 如何读写二进制文件_c++文件I/O与二进制数据读写方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号