st_mode

st_mode的剖析

最近在写code时,需要频繁使用到stat函数,为了更好的容错和log,就需要利用好st_mode。ok, 先看一下struct stat的结构。struct stat {dev_t         st_dev;      /* device */ino_t         st_ino;      /* inode */mode_t        st_mode;     /* protection */nlink_t       st_nlink;    /* number of hard links */uid_t         st_uid;      /* user ID of owner */gid_t         st_gid;      /* group ID of owner */dev_t         st_rdev;     /* device type (if inode device) */off_t         st_size;     /* total size, in bytes */blksize_t     st_blksize;  /* blocksize for filesystem I/O */blkcnt_t      st_blocks;   /* number of blocks allocated */time_t        st_atime;    /* time of last access */time_t        st_mtime;    /* time of last modification */time_t        st_ctime;    /* time of last status change */};其中,st_mode的类型 mode_t.mode_t其实就是普通的unsigned int.目前,st_mode使用了其低19bit. 0170000 => 1+ 3*5 = 16.其中,最低的9位(0-8)是权限,9-11是id,12-15是类型。具体定义如下:S_IFMT     0170000   bitmask for the file type bitfieldsS_IFSOCK   0140000   socketS_IFLNK    0120000   symbolic linkS_IFREG    0100000   regular fileS_IFBLK    0060000   block device       S_IFDIR    0040000   directoryS_IFCHR    0020000   character deviceS_IFIFO    0010000   fifoS_ISUID    0004000   set UID bitS_ISGID    0002000   set GID bit (see below)S_ISVTX    0001000   sticky bit (see below)S_IRWXU    00700     mask for file owner permissionsS_IRUSR    00400     owner has read permissionS_IWUSR    00200     owner has write permissionS_IXUSR    00100     owner has execute permissionS_IRWXG    00070     mask for group permissionsS_IRGRP    00040     group has read permissionS_IWGRP    00020     group has write permissionS_IXGRP    00010     group has execute permissionS_IRWXO    00007     mask for permissions for others (not in group)S_IROTH    00004     others have read permissionS_IWOTH    00002     others have write permissonS_IXOTH    00001     others have execute permission当我们需要快速获得文件类型或访问权限时,最好的方法就是使用glibc定义的宏。如:S_ISDIR,S_IRWXU等。例:如果我们需要知道一个文件类型struct stat tmpStat;memset(&tmpStat, 0, sizeof(struct stat));stat("/tmp", &tmpStat);cout.setf(ios::oct, ios::basfield);cout << (tmpStat.st_mode & S_IFMT) << endl;输出:40000根据之前的定义,我们知道40000表示目录;同理,如果我们需要知道一个文件权限只需cout << (tmpStat.st_mode & ALLPERMS) << endl;输出:1777为什么会多出前面的1呢?我暂时认为可能还9-11位的id field有关。如果别的目录,显示是正常的。如755.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值