Why these lines of code doesn't work when i try to read a DWORD num = 1880762702
using fread(&num, "file path", 1, FILE*);
I get the result = 10574
if I change the num to any other number say 2880762702
only then it works.
views:
115answers:
2
+3
A:
To read a multibyte quantity such as a DWORD (which is Win32-speak for a 32-bit number) you need to be aware of endianness. It's best to read the number one byte at a time, and convert from the byte ordering used in the file.
FILE *in;
DWORD num = 0;
if((fin = fopen("filename.bin", "rb")) != NULL)
{
unsigned char b0, b1, b2, b3;
fread(&b3, sizeof b3, 1, in);
fread(&b2, sizeof b2, 1, in);
fread(&b1, sizeof b1, 1, in);
fread(&b0, sizeof b0, 1, in);
// Assuming file is big-endian.
// for little endian, swap the order to b0...b3
num = (((DWORD) b3) << 24) | (((DWORD) b2) << 16) | (((DWORD) b1) << 8) | b0;
fclose(in);
}
unwind
2010-04-06 07:27:52
+1
A:
The second parameter to fread()
is the size of the data you want to read. In your case, that's sizeof(DWORD)
.
Aaron Digulla
2010-04-06 07:29:01