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 bitfields
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
S_ISUID    0004000   set UID bit
S_ISGID    0002000   set GID bit (see below)
S_ISVTX    0001000   sticky bit (see below)
S_IRWXU    00700     mask for file owner permissions
S_IRUSR    00400     owner has read permission
S_IWUSR    00200     owner has write permission
S_IXUSR    00100     owner has execute permission
S_IRWXG    00070     mask for group permissions
S_IRGRP    00040     group has read permission
S_IWGRP    00020     group has write permission
S_IXGRP    00010     group has execute permission
S_IRWXO    00007     mask for permissions for others (not in group)
S_IROTH    00004     others have read permission
S_IWOTH    00002     others have write permisson
S_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.
原文地址:https://www.cnblogs.com/pythonschool/p/2792931.html