C语言中的fread如何工作? [英] how fread works in C?
问题描述
我有一个文本文件,其内容为:
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]);
}
我得到了结果:
我无法解释自己为什么得到这样的结果.
I cannot explain myself why I got such results.
推荐答案
文本文件与二进制文件
您在应该用于二进制文件的文本文件上误用了fread
函数. 文本文件与
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.
假设,如果您保存带有四个 ASCII字符的txt "1"
,"2"
,"3"
,"4"
,实际上存储在磁盘上的不是1
,2
,3
,4
.而是它们的ACSII代码:49
,50
,51
,52
.
因此,当您将sizeof(a[0])
字节读入a[0]
时,将在内存中读回四个字节,如:
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 一个>.简而言之,如果您的平台是little-endian(例如Intel x86处理器),则最低内存地址(0x12345678
)上的第一个字节(00110001
)将是形成整数的最低有效字节.
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.
最终,整数以二进制形式为00110100001100110011001000110001
,即以十进制形式为875770417
.
Eventually, the integer is 00110100001100110011001000110001
in binary, that's 875770417
in decimal.
这篇关于C语言中的fread如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!