使用ofstream写入二进制文件需以std::ios::binary模式打开,并用write()写入原始字节数据。

在C++中使用
ofstream
write()
使用
std::ofstream
open()
std::ios::binary
std::ofstream file("data.bin", std::ios::binary);
if (!file) {
<strong>std::cerr << "无法打开文件!" << std::endl;</strong>
return -1;
}
使用
write()
write()
int value = 42; float fval = 3.14f; file.write(reinterpret_cast<const char*>(&value), sizeof(value)); file.write(reinterpret_cast<const char*>(&fval), sizeof(fval));
注意:
reinterpret_cast
const char*
write()
立即学习“C++免费学习笔记(深入)”;
对于数组或自定义结构体,同样使用
write()
int arr[] = {1, 2, 3, 4, 5};
file.write(reinterpret_cast<const char*>(arr), sizeof(arr));
struct Point {
float x, y;
};
Point p{1.5f, 2.5f};
file.write(reinterpret_cast<const char*>(&p), sizeof(p));
注意:结构体可能存在内存对齐填充,跨平台读取时需谨慎处理。
写入完成后,应显式调用
close()
file.close();
即使析构函数会自动关闭,显式调用更安全,尤其需要检查是否写入成功时。
基本上就这些。只要记得用
binary
write()
reinterpret_cast
以上就是C++如何使用ofstream写入二进制文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号