Parsing a binary file. What is a modern way?

后端 未结 10 2040
悲哀的现实
悲哀的现实 2021-01-30 01:41

I have a binary file with some layout I know. For example let format be like this:

  • 2 bytes (unsigned short) - length of a string
  • 5 bytes (5 x chars) - the
10条回答
  •  余生分开走
    2021-01-30 02:04

    Since all of your data is variable, you can read the two blocks separately and still use casting:

    struct id_contents
    {
        uint16_t len;
        char id[];
    } __attribute__((packed)); // assuming gcc, ymmv
    
    struct data_contents
    {
        uint32_t stride;
        float data[];
    } __attribute__((packed)); // assuming gcc, ymmv
    
    class my_row
    {
        const id_contents* id_;
        const data_contents* data_;
        size_t len;
    
    public:
        my_row(const char* buffer) {
            id_= reinterpret_cast(buffer);
            size_ = sizeof(*id_) + id_->len;
            data_ = reinterpret_cast(buffer + size_);
            size_ += sizeof(*data_) + 
                data_->stride * sizeof(float); // or however many, 3*float?
    
        }
    
        size_t size() const { return size_; }
    };
    

    That way you can use Mr. kbok's answer to parse correctly:

    const char* buffer = getPointerToDataSomehow();
    
    my_row data1(buffer);
    buffer += data1.size();
    
    my_row data2(buffer);
    buffer += data2.size();
    
    // etc.
    

提交回复
热议问题