天天看点

Linux 函数--fstat/stat/lstat系统调用

【fstat/stat/lstat系统调用】  

功能描述:  

获取一些文件相关的信息。

用法:  

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

int stat(const char *path, struct stat *buf);

int fstat(int filedes, struct stat *buf);

int lstat(const char *path, struct stat *buf);

参数:  

path:文件路径名。

filedes:文件描述词。

buf:是以下结构体的指针

struct stat {

    dev_t     st_dev;    

     ino_t     st_ino;    

   mode_t    st_mode;   

   nlink_t   st_nlink;  

   uid_t     st_uid;    

   gid_t     st_gid;    

   dev_t     st_rdev;   

   off_t     st_size;   

   blksize_t st_blksize;

   blkcnt_t  st_blocks; 

   time_t    st_atime;  

   time_t    st_mtime;  

   time_t    st_ctime;  

};

返回说明:  

成功执行时,返回0。失败返回-1,errno被设为以下的某个值  

EBADF:  文件描述词无效

EFAULT: 地址空间不可访问

ELOOP:  遍历路径时遇到太多的符号连接

ENAMETOOLONG:文件路径名太长

ENOENT:路径名的部分组件不存在,或路径名是空字串

ENOMEM:内存不足

ENOTDIR:路径名的部分组件不是目录  

 文件和目录

                       stat,fstat和lstat函数

 #i nclude<sys/stat.h>

 int stat(const char *restrict pathname,struct stat *restrict buf);

 int fstat(int fields,struct stat *buf);

 int lstat(const char *restrict pathname,struct stat *restrict buf);

 返回值:若成功则返回0,失败则返回-1

 一旦给出pathname,stat函数就返回与此命名文件有关的信息结构,fstat函数获取已在描述符fields上打开文件的有关信息。

 lstat函数类似于stat.但是当命名的文件是一个符号链接时,lstat返回该符号链接的有关信息,而不是由该符号链接引用文件

 的信息。第二个参数buf是指针,它指向一个我们必须提供的结构,这些函数填写由buf指向的结构。该结构的实际定义可能随实现

 有所不同.

   struct stat{

    mode_t  st_mode;     //文件类型和权限信息

    ino_t   st_ino;      //i结点标识

    dev_t   st_dev;      //device number (file system)

    dev_t   st_rdev;     //device number for special files

    nlink_t st_nlink;    //符号链接数

    uid_t   st_uid;      //用户ID

    gid_t   st_gid;      //组ID

    off_t   st_size;     //size in bytes,for regular files

    time_t  st_st_atime; //最后一次访问的时间

    time_t  st_mtime;    //文件内容最后一次被更改的时间

    time_t  st_ctime;    //文件结构最后一次被更改的时间

    blksize_t st_blksize; //best I/O block size

    blkcnt_t st_blocks;  //number of disk blocks allocated

   };

文件类型:

  普通文件,目录文件,块特殊文件,字符特殊文件,套接字,FIFO,符号链接.

  文件类型信息包含在stat结构的st_mode成员中,可以用如下的宏确定文件类型,这些宏是stat结构中的st_mode成员.

  S_ISREG();S_ISDIR();S_ISCHR();S_ISBLK();S_ISFIFO();S_ISLNK();S_ISSOCK()

  示例:

     #i nclude<iostream>

     int main(int argc,char* argv[])

     {

          int i;

        struct stat buf;

        char * ptr;

        for(i=1;i<argc;i++)

         {

            if(lstat(argv[i],&buf)<0)

               {

                 perror("错误原因是:");

                 continue;

               }

            if (S_ISREG(buf.st_mode))

                ptr="普通文件";

            if (S_ISDIR(buf.st_mode))

                ptr="目录";

            //......and so on...

           cout<<"参数为:"<<argv[i]<<"的标识是一个"<<ptr<<endl;

         }

        exit(0);

     }

继续阅读