#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main()
{
FILE* bmp = NULL;
uint32_t offset;
uint8_t* temp = NULL;
size_t read;
unsigned int x_dim = 600, y_dim = 388;
bmp = fopen("test_colour.bmp", "r");
if (!bmp)
return -1;
/* Get the image data offset */
fseek(bmp, 10, SEEK_SET);
fgets((char*)&offset, 4, bmp);
printf("Offset = %u\n", offset);
temp = malloc(3*x_dim*y_dim*sizeof(uint8_t));
if (!temp)
return -1;
/* Go the the position where the image data is stored */
fseek(bmp, offset, SEEK_SET);
/* Copy image data to array */
printf("%u bytes requested!\n", 3*x_dim*y_dim);
read = fread((void*)temp, sizeof(uint8_t), 3*x_dim*y_dim, bmp);
printf("%Iu bytes read!\n", read);
fclose(bmp);
free(temp);
return 0;
}
I'm using the above code to read the RGB data of a 24-bit per pixel BMP image to an array. The offset from the start of file where the image data starts (after the BMP header) is given at offset 10 according to the BMP specification. I get the following output when executing the above code.
Offset = 54
698400 bytes requested!
33018 bytes read!
The offset output seems to be correct because the file size is 698454 bytes (=698400+54). However, the value returned by fread()
seems to indicate that not the entire image data could be read. However, I'm subsequently using the data in the temp
array to convert the RGB data to greyscale and writing this data to a BMP file again. Visually checking the output image does not indicate any errors, i.e. it seems as if I actually read the entire input image in the first place although fread()
seems to indicate differently.
Can someone explain this behaviour?
temp
after the call tofread
, to see if it actually stopped reading after 33018 bytes? 2) I am unfamiliar with%Iu
format specifier - can you check the actual value ofread
in the debugger? – Avignonprintf
format strings. The format forsize_t
is"%zu"
."%Iu"
is non-standard. If your implementation doesn't support"%zu"
, you can useprintf("%lu bytes read!\n", (unsigned long)read);
– Tetreault%zu
specifier (I tried using that one before). I read that one has to use%Iu
in windows. – Dieballprintf()
format specifiers supported. Newer MinGW releases and/or newer versions of MSVCRT.DLL seem to support more and more of the C99 standard specifiers. – Motonbmp
file (600*388 pixels), the size I found is 698454 and i could read 698400 bytes (from Offset). you can try another file... copy it in another location.. (possible disk error). – Gleeson"rb"
. The only problem seems to be using"r"
under Windows. – Dieball