本文介绍了我怎样才能读取BMP文件,并通过结构指针访问它的头信息,而不使用#pragma pack或__atribute __((包装))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code。我想知道如何正确读BMP文件,然后读取标头值而不强制结构来进行包装。

  typedef结构__attribute __((包装)){
uint8_t有魔术[2]; / *用于识别BMP文件的幻数:
                     0x42后送出0x4d(对于B和M进制code点)。
                     下面的条目:
                     BM - 的Windows 3.1,95,NT,...等
                     BA - OS / 2位图阵列
                     CI ​​- OS / 2彩色图标
                     CP - OS / 2彩色指针
                     IC - OS / 2图标
                     PT - OS / 2指针。 * /
uint32_t的filesz; / * BMP文件的字节大小* /
uint16_t creator1; / *保留。 * /
uint16_t creator2; / *保留。 * /
uint32_t的偏移; / *偏移,即起始地址,
                     的,其中位图数据可以发现的字节。 * /
} bmp_header_t;FP = FOPEN(input.bmp,R);
bmp_header_p =的malloc(sizeof的(bmp_header_t));FREAD(bmp_header_p,sizeof的(焦炭),14,FP);的printf(幻数=%C%C \\ N,bmp_header_p->魔术[0],bmp_header_p->魔术[1]);
的printf(文件大小=%PRIu32\\ n,bmp_header_p-> filesz);


解决方案

您不要 FREAD()成一旦整个结构。相反,你 FREAD()分别进入其领域,像这样的:

 如果(FREAD(安培;报头 - >!魔法[0],2,1,FP)= 1){
    //错误
}如果(的fread(安培;报头 - >!filesz,4,1,FP)= 1){
    //错误
}

Here is my code. I would like to know how to "properly" read the BMP file and then read the header values without forcing the struct to be packed.

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, i.e. 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);
解决方案

You don't fread() into the entire struct at once. Instead, you fread() into its fields separately, like this:

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

if (fread(&header->filesz, 4, 1, fp) != 1) {
    // error
}

这篇关于我怎样才能读取BMP文件,并通过结构指针访问它的头信息,而不使用#pragma pack或__atribute __((包装))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 00:21