昨天看代码,看到一个问题,在linux下求一个文件的实际的大小,代码中用的方法是反复的调用fseek函数和ftell函数。如于之前用过stat的,所以就和同事讨论了一下为什么不用stat,下面是这两种方法的比较。具体的程序如下:
1 、用fseek函数和ftell函数实现。
#include
#include
#include
#include
int main()
{
FILE * fp;
int head;
int tail;
int sum=0;
struct timeval tv1,tv2;
struct timezone tz;
gettimeofday(&tv1,&tz);
printf("tv_sec is :%d\n tv_usec is :%d\n",tv1.tv_sec,tv1.tv_usec);
if((fp=fopen("vm1.rar","rb"))==NULL)
{
perror("open the file failer!");
return -1;
}
fseek(fp,0,SEEK_SET);
head=ftell(fp);
//printf("the head is %d \n",head);
fseek(fp,0,SEEK_END);
tail=ftell(fp);
//printf("the tail is %d \n",tail);
fseek(fp,0,SEEK_SET);
sum=tail-head;
printf("the file size is %d \n",sum);
gettimeofday(&tv2,&tz);
printf("tv_sec is : %d\n tv_usec is : %d\n",tv2.tv_sec,tv2.tv_usec);
printf("the operation time is %d s : %d us \n",tv2.tv_sec-tv1.tv_sec,tv2.tv_usec-tv1.tv_usec);
return 0;
}
运行的结果为:
2 、下面是使用stat的程序。
#include
#include
#include
#include
#include
int main()
{
struct stat buf;
struct timeval tv1,tv2;
struct timezone tz;
gettimeofday(&tv1,&tz);
printf("tv_sec is :%d\n tv_usec is :%d\n",tv1.tv_sec,tv1.tv_usec);
stat("vm1.rar",&buf);
printf("the file size is =%d \n",buf.st_size);
gettimeofday(&tv2,&tz);
printf("tv_sec is : %d\n tv_usec is : %d\n",tv2.tv_sec,tv2.tv_usec);
printf("the operation time is %d s : %d us \n",tv2.tv_sec-tv1.tv_sec,tv2.tv_usec-tv1.tv_usec);
}
程序的运行结果为:
3、比较。
两者读取到的文件的实际大小是没有问题的。在windows下单击被读取的文件属性获得的文件实际的大小是:
。
从而,程序两者获取文件的实际大小是没有问题的。再看,两者的执行时间,就可以比较出来了!第一种情况执行的时间是428微妙,第二种情况执行的时间是249微妙。