简体   繁体   English

C ++要结构化的二进制文件

[英]C++ Binary file to struct

I'm trying to read some data from a binary file. 我正在尝试从二进制文件中读取一些数据。

I have a struct set up that looks something like this: 我有一个结构设置,看起来像这样:

struct track{
    unsigned long   ID;                             
    string      title;                      
};

And a file that stores values like 还有一个存储值的文件

    [00000001][5468652054726163]
    [00000002][6F776C6F6F6B6174]

This is my terrible logic in somewhat pseudocode, 这是我在某种伪代码中的可怕逻辑,

blocksize = 4;     // Read 4 bytes at a time

while(!endoffile){
    track[i].ID = (blocksize,pos)        // get 4 bytes starting at position
    track[i].title = blocksize*2,pos+4)  // get 8 bytes starting 4 after last position
    pos+12; i++;
}

I'm sorry, it's so bad. 对不起,这太糟糕了。 Like I said I'm new to C++. 就像我说我是C ++的新手。 I know how to use fstream etc, it's just the logic of cycling through bytes in binary that throws me completely off. 我知道如何使用fstream等,它只是循环通过二进制字节的逻辑,完全抛弃了我。

You can do something like this: 你可以这样做:

#include <cstdint>
#include <fstream>
#include <string>

struct track { uint32_t id; char title[8]; };

std::ifstream infile("thefile.bin");

for (;;)
{
    track t;

    if (!infile.read(reinterpret_cast<char*>(&t.id), 4) ||
        !infile.read(t.title, 8)                        ||
        infile.gcount() != 8)
    {
        // error, die (or perhaps end of file)
    }

    // now you can use "t", e.g.:

    std::string title(t.title, 8);    // a sane string object
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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