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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM