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 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.
You have a text file, but fread reads binary data. So you're storing the bytes from the file rather than the text of the file. Try using fread to populate your unused buffer variable instead and you should be able to get the textual string which you can then parse using e.g. sscanf(). Or you could stop using fread and use fscanf instead.
That is the correct result. You are reading the data as binary data, not text or integers. The first four bytes are 0x31323334, which when read on an Intel machine flips to 0x34333231 which is 875770417 in decimal.
来源:https://stackoverflow.com/questions/10259344/how-fread-works-in-c