如何在不使用#pragma pack或__atribute __((packed))的情况下通过结构指针读取BMP文件并访问其标题信息?

这是我的代码。 我想知道如何“正确”读取BMP文件然后读取标头值而不强制结构被打包。

typedef struct __attribute__((packed)){ uint8_t magic[2]; /* the magic number used to identify the BMP file: 0x42 0x4D (Hex code points for B and M). The following entries are possible: BM - Windows 3.1x, 95, NT, ... etc BA - OS/2 Bitmap Array CI - OS/2 Color Icon CP - OS/2 Color Pointer IC - OS/2 Icon PT - OS/2 Pointer. */ uint32_t filesz; /* the size of the BMP file in bytes */ uint16_t creator1; /* reserved. */ uint16_t creator2; /* reserved. */ uint32_t offset; /* the offset, ie starting address, of the byte where the bitmap data can be found. */ } bmp_header_t; fp = fopen("input.bmp", "r"); bmp_header_p = malloc(sizeof(bmp_header_t)); fread(bmp_header_p, sizeof(char), 14, fp); printf("magic number = %c%c\n", bmp_header_p->magic[0], bmp_header_p->magic[1]); printf("file size = %" PRIu32 "\n", bmp_header_p->filesz); 

你不会立刻fread()到整个结构中。 相反,你将fread()放入其字段中,如下所示:

 if (fread(&header->magic[0], 2, 1, fp) != 1) { // error } if (fread(&header->filesz, 4, 1, fp) != 1) { // error } 

如果您不想打包结构,则必须阅读每个字段并进行适当设置:

 fread(bmp_header_p->magic, sizeof bmp_header_p->magic, 1, fp); fread(&bmp_header_p->filesz, sizeof bmp_header_p->filesz, 1, fp); fread(&bmp_header_p->creator1, sizeof bmp_header_p->creator1, 1, fp); 

… 等等。 如果有必要,您可能需要检查并修复字节顺序,因为可移植性似乎是您的一个问题。 别忘了添加一些错误检查!