使用fstream操作二进制文件需指定std::ios::binary标志,通过write()和read()函数以char*指针形式读写原始字节,适用于POD类型,注意跨平台对齐和数据兼容性问题。

在C++中,使用fstream读写二进制文件是处理非文本数据的常见需求,比如图像、音频、序列化对象等。与文本模式不同,二进制模式能确保数据原样读写,不会被系统转换(如换行符替换)。下面详细介绍如何正确使用fstream进行二进制文件操作。
使用std::fstream、std::ifstream或std::ofstream时,需指定std::ios::binary标志,以确保以二进制模式打开文件。
示例代码:
std::ofstream outFile("data.bin", std::ios::out | std::ios::binary);
std::ifstream inFile("data.bin", std::ios::in | std::ios::binary);
std::fstream file("data.bin", std::ios::in | std::ios::out | std::ios::binary);
如果不加std::ios::binary,在Windows系统上可能会出现数据被意外修改的情况。
立即学习“C++免费学习笔记(深入)”;
使用write()成员函数将内存中的原始字节写入文件。该函数接受一个const char*指针和要写入的字节数。
例如,保存一个整数数组:
int data[] = {10, 20, 30, 40};
outFile.write(reinterpret_cast
// 或者更清晰:
outFile.write(reinterpret_cast
注意:必须使用reinterpret_cast将任意类型指针转为char*,因为write()只接受字符指针。
使用read()函数从文件中读取指定数量的字节到内存缓冲区。
继续上面的例子:
int readData[4];
inFile.read(reinterpret_cast
读取后建议检查是否成功:
if (inFile) {
// 读取成功
} else {
// 可能读到了文件末尾或出错
}
也可以用gcount()获取实际读取的字节数。
对于结构体或类对象,可以直接读写整个对象的内存映像,但要注意以下几点:
示例:
struct Point {
float x, y;
};
Point p{1.5f, 2.5f};
outFile.write(reinterpret_cast
Point p2;
inFile.read(reinterpret_cast
基本上就这些。只要记住用binary模式、正确使用read/write、注意类型转换和数据兼容性,就能安全地操作二进制文件。
以上就是C++如何使用fstream读写二进制文件_C++文件输入输出流操作详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号