1

これが私のコードです。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, 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);
4

2 に答える 2

2

構造体をパックしたくない場合は、各フィールドを読み取って適切に設定する必要があります。

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);

... 等々。移植性が懸念されるように思われるため、必要に応じてエンディアンも確認して修正することをお勧めします。エラーチェックを追加することを忘れないでください!

于 2013-06-22T20:45:21.507 に答える
2

fread()一度に構造体全体に入る必要はありません。代わりに、次のようfread()に、そのフィールドを個別に入力します。

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

if (fread(&header->filesz, 4, 1, fp) != 1) {
    // error
}
于 2013-06-22T20:45:31.137 に答える