【问题标题】:problem writing bitmap file header in C在 C 中写入位图文件头的问题
【发布时间】:2011-04-10 12:19:32
【问题描述】:

我正在尝试使用 C 创建一个新的位图文件。这是 .bmp 文件头的结构。

#define uint16 unsigned short
#define uint32 unsigned long
#define uint8  unsigned char
typedef struct 
{
 uint16 magic;  //specifies the file type "BM" 0x424d
 uint32 bfSize;  //specifies the size in bytes of the bitmap file
 uint16 bfReserved1;  //reserved; must be 0
 uint16 bfReserved2;  //reserved; must be 0
 uint32 bOffBits;  
} BITMAPFILEHEADER;

在我的程序中,我正在这样做。

main() {
FILE* fp;
fp = fopen("test.bmp", "wb");
 BITMAPFILEHEADER bmfh;
 BITMAPINFOHEADER bmih;

 bmfh.magic = 0x4d42; // "BM" magic word
 bmfh.bfSize = 70; 
 bmfh.bfReserved1 = 0;  
 bmfh.bfReserved2 = 0; 
 bmfh.bOffBits = 54; 
fwrite(&bmfh, sizeof(BITMAPFILEHEADER), 1, fp);
fclose(fp);
}

所以,当我读取我的 test.bmp 文件时,它应该包含 14 个字节(stuct 的大小)并且值应该是

42 4d 46 00 00 00 00 00 00 00 36 00 00 00

但如果我读取文件,它会显示 16 个字节:

42 4d 04 08 46 00 00 00 00 00 00 00 36 00 00 00

这个“04 08”是从哪里来的。? 我的 bmp 文件损坏了。

我的问题是,在二进制文件 I/O 中,如果我将结构写入文件并且其大小不是 4Bytes(32 位)的倍数,它会自动更改结构吗?

知道如何解决这个问题吗?

【问题讨论】:

    标签: c file-io bitmap binaryfiles


    【解决方案1】:

    您的结构正在被填充。 04 08 是堆栈中的垃圾值。您需要使用编译器提供的任何功能来打包结构。在大多数情况下,您应该可以使用#pragma pack(1)

    #pragma pack(1)  // ensure structure is packed
    typedef struct 
    {
       .
       .
       .
    } BITMAPFILEHEADER;
    #pragma pack(0)  // restore normal structure packing rules
    

    你可以在维基百科上阅读data structure padding

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-18
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多