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

C++ Binary file to struct

本文关键字:二进制文件 C++ 结构      更新时间:2023-10-16

我正试图从二进制文件中读取一些数据。

我设置了一个结构,看起来像这样:

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

以及一个存储等值的文件

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

这是我在某种程度上伪代码中的糟糕逻辑

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++;
}

对不起,太糟糕了。就像我说的,我是C++新手。我知道如何使用fstream等,只是在二进制文件中循环字节的逻辑让我完全失望。

您可以这样做:

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