Search code examples
ceclipsemingwfwritebmp

fwrite() c function writing extra bytes


I'm using eclipse for c (Version: 2020-03 (4.15.0) Build id: 20200313-1211) and MinGW (version 0.6.3-pre-20170905-1).

I have been playing with fwrite() for the past few weeks, mainly creating BMP files, without any weird problems.

Something really strange is happening now that I do not understand at all: the resulting file has 2 extra bytes and thus the image is corrupted and can not be displayed.

  • I have read the value that fwrite() returns and is equal to the size meant to write (384 both cases)
  • I have checked the data of the pointer given to fwrite() and the internal (FILE*)->_base and both point to an address with the correct content, but different from what the generated file has.

And when deleting this 2 bytes, the image is perfectly readable (I use the software HxD).

This is the generated file, the 2 bytes are the 0D before the two 0A 00 00 00 (which are the width and height) are these extra bytes that I don't have a clue where they come from, and because where are located, they offset all the other BMP header info and corrupt the image!

Contents of the corrupted BMP file

The BMP is nothing fancy at all, just a 10x10px square with a grayscale gradient.

Thanks in advance!


Solution

  • Wow, thanks to everyone for your fast answers!

    Indeed was the \nconverted to \r\n issue. Creating the file as binary (fopen(<>,"wb")) has solved the issue!

    Thanks tkausl and Johnny Mopp ! Thanks to everyone, you are amazing people!