C++:stat函数

函数原型:int stat(const char *pathname, struct stat *statbuf)

函数作用:用于获取文件状态信息

使用函数需要包含头文件:

       #include <sys/types.h>
       #include <sys/stat.h>
       #include <unistd.h>

stat函数在 statbuf 指向的缓冲区中返回有关文件的信息。 

返回值:成功返回0;失败返回-1

stat结构:
函数调用返回一个 stat 结构,其中包含以下字段: 

struct stat 
        {
            dev_t     st_dev;         /* ID of device containing file */文件使用的设备号
            ino_t     st_ino;         /* Inode number */ 索引节点号
            mode_t    st_mode;        /* File type and mode */文件类型和模式
            nlink_t   st_nlink;       /* Number of hard links */文件的硬连接数
            uid_t     st_uid;         /* User ID of owner */所有者的用户ID
            gid_t     st_gid;         /* Group ID of owner */所有者的组ID
            dev_t     st_rdev;        /* Device ID (if special file) */设备ID
            off_t     st_size;        /* Total size, in bytes */以字节为单位的文件容量
            blksize_t st_blksize;     /* Block size for filesystem I/O */文件系统 I/O块大小
            blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */文件所占的磁盘块

            /* 自 Linux 2.6 起,内核支持纳秒以下时间戳字段的精度。
                           Linux 2.6 之前的详细信息,请参见注释。 */

            struct timespec st_atim;  /* Time of last access*/最后一次访问该文件的时间
            struct timespec st_mtim;  /* Time of last modification*/最后一次修改该文件的时间
            struct timespec st_ctim;  /* Time of last status change*/最后一次修改文件状态的时 
            间

            #define st_atime st_atim.tv_sec      /* 向后兼容 */
            #define st_mtime st_mtim.tv_sec
            #define st_ctime st_ctim.tv_sec
           };

stat结构体中的st_mode 为文件类型定义了以下掩码值:

           S_IFMT     0170000   bit mask for the file type bit field
           S_IFSOCK   0140000   socket
           S_IFLNK    0120000   symbolic link
           S_IFREG    0100000   regular file
           S_IFBLK    0060000   block device
           S_IFDIR    0040000   directory
           S_IFCHR    0020000   character device
           S_IFIFO    0010000   FIFO

POSIX 还定义了额外的宏,以允许在 st_mode 中编写文件类型的测试更简洁。 

           S_ISREG(m)  is it a regular file?

           S_ISDIR(m)  directory?

           S_ISCHR(m)  character device?

           S_ISBLK(m)  block device?

           S_ISFIFO(m) FIFO (named pipe)?

           S_ISLNK(m)  symbolic link?  (Not in POSIX.1-1996.)

           S_ISSOCK(m) socket?  (Not in POSIX.1-1996.)

测试例子:

stat(pathname, &sb);
if (S_ISREG(sb.st_mode))
 {
 /* Handle regular file */
 }
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值