Text file vs. Binary file
You misuse the fread
function on a text file which is supposed to be used on a binary file. A text file is different with a binary file.
Let's say, if you save txt with four ASCII characters "1"
, "2"
, "3"
, "4"
, what's actually stored on disk is not 1
, 2
, 3
, 4
. Instead, it's their ACSII codes: 49
, 50
, 51
, 52
.
So when you read sizeof(a[0])
bytes into a[0]
, four bytes are read back in memory like:
Memory Address Byte In Memory Little-endian
0x12345678 00110001 <----least significant byte
0x12345679 00110010
0x12345680 00110011
0x12345681 00110100 <----most significant byte
(Note that address is just faked for illustration)
Endianness
As to how these four bytes are converted into an integer, it all has something to do with Endianness. In short, if your platform is little-endian(e.g., Intel x86 processor), the first byte(00110001
) on the lowest memory address(0x12345678
) will be the least significant byte to form the integer.
Eventually, the integer is 00110100001100110011001000110001
in binary, that's 875770417
in decimal.