问题写C位图文件头 [英] problem writing bitmap file header in C

查看:161
本文介绍了问题写C位图文件头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a new bitmap file using C. This is a struct for the .bmp file header.

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

在我的计划,我这样做。

In my program I am doing this.

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的大小)和值应

So, when I read my test.bmp file it should contain 14 bytes (size of the stuct) and the values should be

42 4D 46 00 00 00 00 00 00 00 36 00 00 00

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

但是,如果我读文件就说明我的16个字节:

But if I read the file it shows me 16 bytes:

42 4D 04 08 46 00 00 00 00 00 00 00 36 00 00 00

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

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

From where does this "04 08" come.? My bmp file becomes corrupted.

我的问题是,在二进制文件I / O如果我写的结构到一个文件,它的大小是不4字节(32位)的倍数,它会自动改变结构?

My question is that in binary file I/O if I write a structure to a file and its size is not multiple of 4Bytes (32 bit), does it automatically change the structure?

不知道如何使用此解决?

Any idea how to get around with this?

推荐答案

您结构正在填充。在 04 08 是你的筹码垃圾值。您需要使用什么功能,你的编译器提供以封装结构。在大多数情况下,你应该能够使用的#pragma包(1)

Your structure is being padded. The 04 08 is a garbage value from your stack. You need to use whatever feature your compiler provides to pack the structure. In most cases you should be able to use #pragma pack(1):

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

您可以阅读维基百科上数据结构的填充

You can read about data structure padding on wikipedia.

这篇关于问题写C位图文件头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆