结论
当目标还有字节可读时,返回实际读到的字节数。尽量读参数指定的长度,不够的话就能读多少读多少。
无字节可以读时,返回0或者负数。
If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).
测试代码
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *fp;
int ret;
unsigned char *buf;
int i;
if (argc != 2) {
fprintf(stderr, "invalid usage\n");
return -1;
}
fp = fopen(argv[1], "r");
if (!fp) {
fprintf(stderr, "fail to open %s", argv[1]);
return -1;
}
buf = malloc(16);
if (!buf) {
fprintf(stderr, "fail to malloc\n");
goto FAIL_MALLOC;
}
while (1) {
ret = fread(buf, 1, 8, fp);
fprintf(stdout, "fread ret=%d.", ret);
if (ret > 0) {
for (i = 0; i < ret; i++) {
fprintf(stdout, " %c", buf[i]);
}
fprintf(stdout, "1\n");
} else {
break;
}
}
fprintf(stdout, "end\n");
return 0;
FAIL_MALLOC:
fclose(fp);
return -1;
}
在上面的while循环里面,每次读8个字节,读下面的文件:
1234567890
一共十个字节(可能是是一个,读到的第十一个字节ascii码为101)
测试结果为:
./a.out ./1.txt
fread ret=8. 1 2 3 4 5 6 7 81
fread ret=3. 9 0
1
fread ret=0.end
可以看到第一次读了8个字节就结束了(结束符为:1\n
),fread返回值为8
第二次读了3个字节,是: 9、0、换行
第三次就没字节可以读了,返回0