C++中write()和read()用于二进制文件操作,需包含<fstream>并使用std::ios::binary标志以避免数据转换错误;write()将内存数据按字节写入文件,需用reinterpret_cast将指针转为const char*,read()则从文件读取指定字节数到内存,同样需类型转换;适用于基本类型数组和不含指针的结构体,如Person{name, age},但含指针或STL容器的类需自定义序列化;操作后应检查流状态确保读写成功。

在C++中,write() 和 read() 函数用于对二进制文件进行高效的数据读写操作。它们属于
std::ofstream
std::ifstream
<fstream>
使用
std::ofstream
std::ifstream
std::ios::binary
std::ofstream outFile("data.bin", std::ios::binary);
std::ifstream inFile("data.bin", std::ios::binary);
如果不加
binary
write() 函数原型为:
立即学习“C++免费学习笔记(深入)”;
write(const char* buffer, std::streamsize size)
它将内存中从
buffer
size
示例:写入一个整数数组
int arr[] = {10, 20, 30, 40, 50};
std::ofstream out("numbers.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(arr), sizeof(arr));
out.close();
注意:必须使用
reinterpret_cast<const char*>
char*
write()
read() 函数原型为:
read(char* buffer, std::streamsize size)
它从文件读取
size
buffer
示例:读取之前保存的整数数组
int arr[5];
std::ifstream in("numbers.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(arr), sizeof(arr));
in.close();
读取后,
arr
if (in) {
// 读取成功
} else {
// 读取失败,可能文件不存在或数据不完整
}
二进制读写常用于保存结构体。例如:
struct Person {
char name[20];
int age;
};
<p>Person p = {"Alice", 25};</p><p>std::ofstream out("person.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(&p), sizeof(p));
out.close();</p><p>std::ifstream in("person.bin", std::ios::binary);
Person p2;
in.read(reinterpret_cast<char*>(&p2), sizeof(p2));</p>注意:包含指针或STL容器(如
std::string
基本上就这些。只要注意类型转换、二进制标志和数据一致性,
write()
read()
以上就是C++中如何使用write()和read()函数对二进制文件进行操作的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号