在C++中读取二进制模式文件,可以使用std::ifstream
类来打开文件并读取数据。以下是一个示例代码:
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("binary_file.bin", std::ios::binary);
if (!file) {
std::cerr << "Failed to open file!" << std::endl;
return 1;
}
char buffer[256];
while (file.read(buffer, sizeof(buffer))) {
// 处理读取的数据
}
file.close();
return 0;
}
在上面的示例中,我们使用std::ifstream
类打开了一个名为binary_file.bin
的二进制模式文件,并使用std::ios::binary
标志指定了文件的读取模式为二进制模式。然后我们使用read
函数读取数据到缓冲区buffer
中,直到文件末尾为止。最后,记得关闭文件流。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:如何使用C++读取二进制文件