您的位置:首页 > 运维架构 > Linux

Linux下求取文件长度的几种常用方法

2010-11-19 22:43 295 查看
第一类:lseek/fseek

1、lseek

代码片段:
int GetFileSize(char *_pName) 
{
   int iFd = -1;
   int  iLen = 0;
   if (_pName == NULL)
  {
     return -1;
  }
  iFd = open(_pName, O_RDONLY);
  if (iFd >= 0)
  {
     iLen = lseek(iFd, 0, SEEK_END); 
     close(iFd);
    return iLen;
  }
 
 return iFd;


2、fseek+ftell:特别注意文件指针的位置
代码片段
long   GetFileSize(char *_pName )  
      {  
         long  length;
  FILE *fp;
  fp = fopen("_pName ",rw);
  if(fp==NULL)
  return -1;
         fseek(fp,   0L,   SEEK_END);  
         length   =   ftell(fp);
 return length;
      }

第二类:stat、fstat函数族
函数原型:
int stat(char *filename,struct stat *s);
int fstat(int fd,struct stat *s);
代码片段:以stat为例,fstat只是第一个参数用文件描述符。
#include <unstd.h>
#include <sys/stat.h>
int GetFileLen( char *_pName )
{
    struct stat st;
    stat(_pName, &st);
    return st.st_size;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux struct fp null file