(I bet you're on Windows)
bmp = fopen("test_colour.bmp", "r");
it should be
bmp = fopen("test_colour.bmp", "rb");
If the file is opened in text mode on Windows, the runtime will cease to be counted when a byte 0x1a (Ctrl-Z) occurs, which Windows considers the EOF marker for text files. Even if this does not hit Ctrl-Z, you will get corrupted data when Windows converts CR / LF sequences to a single LF character.
However, I cannot explain why you can get a good image from a partial file (just lucky?).
You can render the image from the buffer, because the fread()
implementation reads the number of bytes you requested (or almost so - the number is rounded to a multiple of a certain block size) into the buffer, then it scans the buffer looking for CR / LF sequences for conversion and EOF flags Ctrl -Z.
Thus, although fread()
returns 33018
, the buffer is actually almost completely written with data from the file. The data is not 100% correct (for example, some CR characters probably were dropped) or completed, but in this case they are close enough to display an image that looks as you expected.
Of course, this is simply observing how this particular runtime behaves at present - it may not always behave this way in the future (or even in all systems today).
source share