将数组的各个部分放入结构中

Putting parts of array into struct

本文关键字:结构 个部 数组      更新时间:2023-10-16

我正在解析位图标题(只是为了好玩),但我在将数据放入结构中时遇到问题。这是我的代码:

#include <iostream>
#include <fstream>
using namespace std;
struct bmp_header {
    char16_t id;
    int size;
    char16_t reserved1;
    char16_t reserved2;
    int offset_to_pxl_array;    
} bmp_header;
int main(int argc, char *argv[]) {
    if (argc < 2) {
        cout << "No image file specified." << endl;
        return -1;
    }
    ifstream file(argv[1], ios::in|ios::binary|ios::ate);
    streampos f_size = file.tellg();    
    char *memblock;
    if (!file.is_open()) {
        cout << "Error reading file." << endl;
        return -1;
    }
    memblock = new char[f_size];
    //Read whole file
    file.seekg(0, ios::beg);
    file.read(memblock, f_size);
    file.close();
    //Parse header
    //HOW TO PUT FIRST 14 BYTES OF memblock INTO bmp_header?
    //Output file   
    for(int x = 0; x < f_size; x++) {
        cout << memblock[x];
        if (x % 20 == 0)
            cout << endl;
    }
    cout << "End of file." << endl;
    delete[] memblock;
    return 0;
}

如何将内存块的前 14 个元素放入bmp_header?我一直在尝试在网上搜索一些,但对于这样一个简单的问题,大多数解决方案似乎有点复杂。

最简单的方法是使用 std::ifstream 及其read成员函数:

std::ifstream in("input.bmp");
bmp_header hdr;
in.read(reinterpret_cast<char *>(&hdr), sizeof(bmp_header));

但有一个警告:编译器将对齐bmp_header的成员变量。因此,您必须防止这种情况。例如,在gcc中,您可以通过说__attribute__((packed))来做到这一点:

struct bmp_header {
    char16_t id;
    int size;
    char16_t reserved1;
    char16_t reserved2;
    int offset_to_pxl_array;    
} __attribute__((packed));

此外,正如@ian-cook在下面的评论中指出的那样,字节序也需要注意。