fread() doesn't read short integers?

Started by
4 comments, last by goodperiodical 16 years, 3 months ago
I'm reading in lots of BMP files and I want to read the bitdepth but it is in a 2 byte value.

unsigned short depth[2];
fread(depth, 2, 1, fin);//ERROR
//...
//buffer is a pointer to an array of integers
fread(buffer, 4, data_length, fin);
I should be able to just read the two bytes in separately but I'd like to know how to read a 2 byte value using the cstdlib if it is possible.
Advertisement
You can, but pay attention to endianness. Your code above will read into the first of the two short integers in the array.
Quote:Original post by ToohrVyk
You can, but pay attention to endianness. Your code above will read into the first of the two short integers in the array.
Actually, his code reads 2 bytes, not 2 shorts.
EDIT: Ignore that, I can't read [smile]

fread(depth, 2, 1, fin);
That reads 2 bytes (2*1), you probably want:
fread(depth, sizeof(short), 2, fin);
I've made a mistake! My unsigned short was not actually an array like I thought it was. Thanks for the quick responses.

For anyone interested in the subject, I found this bmp spec very easy to read:
http://www.fortunecity.com/skyscraper/windows/364/bmpffrmt.html
Quote:Original post by goodperiodical
I want to read a 2 byte value one time and this code generates the error:
error C2664: 'fread' : cannot convert parameter 1 from 'int' to 'void *'
The second and third parameters in fread() are element size and count respectively so I believe the line is written correctly but fread() cannot read a 2 byte value.
Yes it can, that's what the second parameter is.

You're passing an int for the first parameter instead of the address of a buffer (E.g. depth in your code).

fread(depth, sizeof(short), 2, fin);
should work fine.

EDIT: Ah, you edited your post [smile]
Quote:Original post by Evil Steve
fread(depth, sizeof(short), 2, fin);
should work fine.

EDIT: Ah, you edited your post [smile]


I know, you beat me to it! Code works fine now. I think that 2 you have there should be a one though. That will read two elements, which would be 4 bytes.

This topic is closed to new replies.

Advertisement