[Linux]文件权限模式掩码常量

一、概述

该系列常量保存在<sys/stat.h>中,《Unix环境高级编程》中的4.9节有提到,这里主要记录一下它们实际对应的值和用法。

二、明细表

常量 DEC OCT BIN
S_ISUID 2048 4000 1000 0000 0000
S_ISGID 1024 2000 0100 0000 0000
S_ISVTX 512 1000 0010 0000 0000
S_IRWXU 448 700 0001 1100 0000
S_IRUSR 256 400 0001 0000 0000
S_IWUSR 128 200 0000 1000 0000
S_IXUSR 64 100 0000 0100 0000
S_IRWXG 56 70 0000 0011 1000
S_IRGRP 32 40 0000 0010 0000
S_IWGRP 16 20 0000 0001 0000
S_IXGRP 8 10 0000 0000 1000
S_IRWXO 7 7 0000 0000 0111
S_IROTH 4 4 0000 0000 0100
S_IWOTH 2 2 0000 0000 0010
S_IXOTH 1 1 0000 0000 0001

三、获取指定权限位的值

通过stat函数获取文件的stat.st_mode,然后和对应的权限位的掩码相与,就可以获取该权限位的值,实际上获取后的值如果等于掩码常量,那么它就具备与之对应的权限:

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>


void main(void)
{
    struct stat container;
    int fd_1 = open("/documents", O_RDONLY);
    int errno = fstat(fd_1, &container);
    int irwxo = container.st_mode & S_IRWXO;
    int iroth = container.st_mode & S_IROTH;
    int iwoth = container.st_mode & S_IWOTH;
    int ixoth = container.st_mode & S_IXOTH;
    printf("errno: %d\n", errno);
    printf("st_mode: %d\n", container.st_mode);
    printf("irwxo: %d\n", irwxo);
    printf("iroth: %d\n", iroth);
    printf("iwoth: %d\n", iwoth);
    printf("ixoth: %d\n", ixoth);
    if(iroth == S_IROTH){
        printf("is readable.\n");
    }
    if(iwoth == S_IWOTH){
        printf("is writable.\n");
    }
    if(ixoth == S_IXOTH){
        printf("is executable.\n");
    }
}

以上代码读取了文件的其他用户权限

posted @ 2020-08-07 10:14  yiyide266  阅读(428)  评论(0编辑  收藏  举报