最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【整理】如何计算文件大小/长度 caculate the file length/size

工作和技术 crifan 1773浏览 0评论

计算文件长度/大小的方法:

方法 1:

infile=fopen(infilename,"rb");

if (!infile) {
printf(" *** Error opening input file %s ***n", infilename);
return -1;
}

/* caculate the file length(bytes) */
chr=fgetc(infile);
while(chr!=EOF){
   ++file_len;
chr=fgetc(infile);
}

缺点:计算速度太慢,而且如果文件稍微大些,其值可能溢出。

方法2:【推荐】通过fseek()和ftell()来获得文件大小

infile=fopen(infilename,"rb");

if (!infile) {
printf(" *** Error opening input file %s ***n", infilename);
return -1;
}

/* caculate the file length(btyes) */
/* 标识符          数值   代表的起始点
    SEEK_SET   0        文件开始
    SEEK_END   2        文件末尾
    SEEK_CUR   1        文件当前位置 */

//fseek(infile,0,2);
fseek(infile,0,SEEK_END);

file_len=ftell(infile);

优点:速度快。

方法3:

#include <sys/stat.h>

if (fstat(STDIN_FILENO, &stat) == -1 || stat.st_size == 0)
    return ;

file_len=stat.st_size;

整理自:

急~~~请教,c语言中有没有那个函数可以计算一个文件的长度的?

转载请注明:在路上 » 【整理】如何计算文件大小/长度 caculate the file length/size

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
79 queries in 0.144 seconds, using 22.09MB memory