linux求文件大小,linux下求文件的实际大小

昨天看代码,看到一个问题,在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;

}

运行的结果为:

0818b9ca8b590ca3270a3433284dd417.png

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);

}

程序的运行结果为:

0818b9ca8b590ca3270a3433284dd417.png

3、比较。

两者读取到的文件的实际大小是没有问题的。在windows下单击被读取的文件属性获得的文件实际的大小是:

0818b9ca8b590ca3270a3433284dd417.png

从而,程序两者获取文件的实际大小是没有问题的。再看,两者的执行时间,就可以比较出来了!第一种情况执行的时间是428微妙,第二种情况执行的时间是249微妙。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值