[英]C++: Reading Binary Files
我有一个二进制文件,该文件具有多个名称,后跟一些详细信息(固定50个字节)。 每个名称后跟0X00,后跟50个字节的详细信息。 我只需要从文件中提取名称。 例如,读取所有字符直到0x00,跳过50个字节并继续到文件末尾。用C ++做到这一点的最佳方法是什么。
#include <fstream>
#include <string>
...
std::ifstream file("filename");
if ( ! file.is_open() )
return;
std::string name;
char data[50];
while ( std::getline( file, name, '\0' ) && file.read( data, 50 ) )
{
// you could use name and data
}
file.close();
...
在“学钓鱼的人”部门: www.cplusplus.com
简化方法:
#include <fstream>
#include <iostream>
int main()
{
char buf[50];
std::ifstream ifs("data.bin", std::ios_base::binary | std::ios_base::in);
while (ifs.read(buf, sizeof(buf)))
{
if (!ifs.eof())
{
std::cout << std::string(buf) << std::endl;
}
}
std::cout << "Done" << std::endl;
ifs.close();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.