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

第一类: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,File,null,FP)