Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 254
  • Last Modified:

Binary File IO in Visual C++

I hope someone can help me as im new to programming and i've hit a brick wall. I want to write the following bytes to a file 0x42, 0x4D, 0x82, 0x88. The bytes form the first part of a windows BMP headder file so need to be exact.

So far i've got the code below but it actually produces the following in the file 0x42, 0x00, 0x00, 0x00, 0x4D, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00,

How do I stop it from putting in the extra 3 bytes in between values?

FILE* f = fopen("grab.bmp", "wb");

if( f == NULL )
{ printf("Error opening file\n");
// Some other error handling code

// Create an integer array to write
int headder[] = {0x42, 0x4D, 0x82, 0x88};

// Write headder to file
int headderWritten = fwrite(headder, sizeof(int), 4, f);

if( fclose(f) != 0 )
printf("Error closing file\n");

Many thanks,

Alex Baskeyfield

No trees were killed during the sending of this message
but a large number of electrons were terribly inconvienced
p.s.  My appologies about the points for the message, its all the points i have left :(

1 Solution
well, for one thing you write the values 4 bytes at a time so o fcourse you get those extra 0 bytes.

You can do one of the following ways to solve the problem:

1. Write one byte at a time.
2. Write the 4 bytes in one bunch.

Method 1 is essentially just looping writing one byte each time, but it's just as easy to use method 2 so I will show method 2 here.

Your main problem is that you declare the array as an array of 'int'. int is 32 bit or 4 bytes so each value stored in the array is 4 bytes. If you want them to be bytes declare the array as an array of bytes instead:

unsigned char headder[4] = {0x42, 0x4D, 0x82, 0x88};

Then write it like this:

int headderwritten = fwrite(headder, sizeof(char), 4, fp);

or some such.

However, a better way is to use the BMP structs defined in windows and so you use something like (I am not sure of the name of the struct etc but you have it in your online help):


// fill in the struct propertly...
bmphdr.iSignature = 0x88824d42;




should work.

No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Answered by: Salte

Please leave any comments here within the next seven days.


EE Cleanup Volunteer

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now