I have text file with content as:
12345678901222344567
Then I used this code to read the content:
FILE * pFile;
int c;
char buffer [256];
pFile = fopen ("myfile.txt","r");
int a[50] = {0};
fread(a, sizeof(a[0]), 5, pFile);
fclose(pFile);
for (c = 0; c < 5; c++)
{
printf("%d\n", a[c]);
}
and I got the results:

I cannot explain myself why I got such results.
Text file vs. Binary file
You misuse the
freadfunction 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 not1,2,3,4. Instead, it’s their ACSII codes:49,50,51,52.So when you read
sizeof(a[0])bytes intoa[0], four bytes are read back in memory like:(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
00110100001100110011001000110001in binary, that’s875770417in decimal.