简体   繁体   English

C ++:读取二进制文件

[英]C++: Reading Binary Files

I have a Binary file that has several names followed by some details (50 bytes fixed). 我有一个二进制文件,该文件具有多个名称,后跟一些详细信息(固定50个字节)。 Each name is followed by 0X00 followed by the 50 byte details. 每个名称后跟0X00,后跟50个字节的详细信息。 I need to extract just the names from the file. 我只需要从文件中提取名称。 ie read all characters till 0x00, skip 50 bytes and continue till end of file.What is the best way to do it in C++. 例如,读取所有字符直到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();
...

In the 'learn a man to fish' department: www.cplusplus.com 在“学钓鱼的人”部门: www.cplusplus.com

Simplistic approach: 简化方法:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM