获取文件大小的方法

方式一:
#include <stdio.h>
#include <sys/stat.h>

unsigned long get_file_size(const char *path)
{
     unsigned long filesize = 0;    
     struct stat statbuff;
     if(stat(path, &statbuff) < 0)
     {
          printf("get file(%s) property failed\n", path);
          return filesize;
     }
     else
     {
          filesize = statbuff.st_size;
     }
    
     return filesize;
}

int main(int argc,char **argv)
{
     int i = 0;
     unsigned long lLen = 0;
    
     for(i = 1; i < argc; i++)
     {
          printf("argc = %d, argv=%s\n",argc,argv[i]);
          lLen = get_file_size(argv[i]);
          printf("S_IFREG=%d,,0x%x, lLen=%lu\n", S_IFREG, S_IFREG,lLen);
     }

    return 0;
}
 
 
方法二:
unsigned long get_file_size_seek(const char *path)
{
     unsigned long filesize = 0;
     long curposition = -1;
     FILE *fp = NULL;
     fp = fopen(path, "r");
     if(fp == NULL)
     {
          printf("fopen file(%s)  failed\n", path);
          return filesize;
     }
     curposition = ftell(fp);
     printf("curposition = %ld\n",curposition);//
curposition =0
    
     if (0 != fseek(fp, 0L, SEEK_END))
     {
          printf("fseek failed \n");
          if (NULL != fp)
          {
               fclose(fp);
               fp = NULL;
          }
     }
    
     filesize = ftell(fp);
     fclose(fp);
     return filesize;
}
 
ftell函数是用来获取文件的当前读写位置;
 
函数原型: long ftell(FILE *fp)
 
函数功能:获取流式文件的当前读写位置,
 
返回值:当前读写位置偏离文件头部的字节数.
 
 
fseek函数是 用来设定文件的当前读写位置.
 
函数原型: int fseek(FILE *fp,long offset,int origin);
 
函数功能:把fp的文件读写位置指针移到指定的位置.
 
fseek(fp,20,SEEK_SET); 意思是把fp文件读写位置指针从文件开始后移20个字节.
posted @ 2015-04-13 22:19  suonikeyinsu  Views(279)  Comments(0Edit  收藏  举报