Sign in to follow this  

fread() doesn't read short integers?

This topic is 3624 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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);

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 3624 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this