fread循环读文件读不完全
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
if(argc!=2)
{
printf("the argc is not enough!\n");
exit(-1);
}
int size;
int ret;
int cur = 0;
FILE *fp = fopen(argv[1], "rb");
//获取文件的大小
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
fseek(fp ,0L, SEEK_SET);
char *buf = (char*)malloc(sizeof(char)*1024);
memset(buf, 0, 1024);
//循环读
do{
ret = fread(buf, sizeof(char), 1024, fp);
cur += ret;
printf("%s", buf);
}while(cur<size);
printf("\n以读取文件大小为:%d\n", cur);
free(buf);
fclose(fp);
return 0;
}
yyt@yyt:~/workspace/apue/tcp/sendfile$ sudo ls -l
总用量 40
-rwxr-xr-x 1 root root 7510 2011-05-11 00:48 read
-rw-r--r-- 1 root root 610 2011-05-11 00:48 read.c
-rwxr-xr-x 1 root root 7957 2011-05-10 22:48 receive
-rw-r--r-- 1 root root 2052 2011-05-10 22:48 receive.c
-rwxr-xr-x 1 root root 12207 2011-05-10 23:39 send
-rw-r--r-- 1 root root 2800 2011-05-10 23:43 send.c
******************************************
然后
yyt@yyt:~/workspace/apue/tcp/sendfile$ sudo ./read send.c
读取文件的大小为2800字节,单还没有把文件读完!!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fread会返回-1,0,>0
printf("%s",buf);会溢出
为什么不用feof()
复制代码
同3L