[RESOLVED] Problem with reading bmp files' headers
Code:
"
struct magic{
char windowsheader[2];
}magicnumbers;
struct bmp {
unsigned int sizeofthefile;
short int applicationspecific1;
short int applicationspecific2;
unsigned int offset;
unsigned int sizeheader;
int width;
int height;
short int colorplanes;
short int btsperpixel;
unsigned int compressionmethod;
unsigned int imagesize;
int horizontalresolution;
int verticalresolution;
unsigned int numberofcolors;
unsigned int numberofimportantcolors;
}bitmap_header;
int main()
{
int windowsheader1[2];
FILE* fp;
if ((fp=fopen("wikipedia.bmp","r"))==NULL)
printf("File error!");
exit(1);
}
fread(&magicnumbers,sizeof(magicnumbers),1,fp);
fread(&bitmap_header,sizeof(bitmap_header),1,fp);
printf("\nwindowsheader:%d %d\n",magicnumbers.windowsheader
[0],magicnumbers.windowsheader[1]);
printf("\napplication specific1:
%d",bitmap_header.applicationspecific1);
printf("\napplication specific2:
%d",bitmap_header.applicationspecific2);
printf("\noffset:%d",bitmap_header.offset);
printf("\nsizeheader:%d",bitmap_header.sizeheader);
printf("\nwidth:%d",bitmap_header.width);
printf("\nheight:%d",bitmap_header.height);
printf("Size of bmp file:%d",bitmap_header.sizeofthefile);
fclose(fp);
"
When I run this program, seems like it is working,at least I am sure that it gives the right file size.
But if I don't use struct magic and instead use:
Code:
struct bmp {
char windowsheader[2];
unsigned int sizeofthefile;
short int applicationspecific1;
short int applicationspecific2;
...//same lines with above
}bitmap_header;
and if I don't use first fread:
Code:
fread(&magicnumbers,sizeof(magicnumbers),1,fp);
then the values which structure "bmp"'s variables get become wrong.
Of course I change the related printf to:
Code:
printf("\nwindowsheader:%d %d\n",bitmap_header.windowsheader[0],bitmap_header.windowsheader[1]);
Why does the problem happen,what is the difference between them?Why do I have to use seperate structs?
Re: Problem with reading bmp files' headers
Your code is faulty in two ways:
1) You must guarantee that the struct is byte aligned. You did not do that or didn't show that in your code (usually a #pragma or compiler option sets the alignment).
2) You must open the file in binary mode, not text mode ("rb", not "r").
Regards,
Paul McKenzie
Re: Problem with reading bmp files' headers
Thank you for your help :)