It looks like you really want to use fread:
int data; fread(&data, sizeof(data), 1, stream);
However, if you want to go the way of reading characters and then reinterpreting them as int, the safe way to do this in C (but not in C ++) is to use union:
union { char theChars[4]; int theInt; } myunion; for(int i=0; i<4; i++) myunion.theChars[i] = fgetc(stream); return myunion.theInt;
I'm not sure why the length of data in your source code is 3. I assume you need 4 bytes; at least I don't know any systems where int is 3 bytes.
Please note that both your code and mine are very non-portable.
Edit: If you want to read ints of various lengths from a file, portable, try something like this:
unsigned result=0; for(int i=0; i<4; i++) result = (result << 8) | fgetc(stream);
(Note: in a real program, you will also want to check the return value of fgetc () for EOF.)
It reads 4-byte unsigned from a little-endian file, regardless of what the consistency of the system is. It should work with almost any system where unsigned has at least 4 bytes.
If you want to be neutral with respect to the end, do not use pointers or unions; use bit shifts instead.
Martin B Jul 14 '10 at 13:01 2010-07-14 13:01
source share