Is there a C function to get permissions of a file?

前端 未结 2 714
孤街浪徒
孤街浪徒 2021-01-19 13:32

I am writing a c program to be run on UNIX, and attempting to utilize the chmod command. After consulting the man pages, i know that chmod needs two parameters. first is the

2条回答
  •  清歌不尽
    2021-01-19 14:38

    The permission can be checked using stat(2), extracting information from S_* flags. Here a function using stat(2):

    #include 
    #include 
    #include 
    #include 
    
    
    int getChmod(const char *path){
        struct stat ret;
    
        if (stat(path, &ret) == -1) {
            return -1;
        }
    
        return (ret.st_mode & S_IRUSR)|(ret.st_mode & S_IWUSR)|(ret.st_mode & S_IXUSR)|/*owner*/
            (ret.st_mode & S_IRGRP)|(ret.st_mode & S_IWGRP)|(ret.st_mode & S_IXGRP)|/*group*/
            (ret.st_mode & S_IROTH)|(ret.st_mode & S_IWOTH)|(ret.st_mode & S_IXOTH);/*other*/
    }
    
    int main(){
    
        printf("%0X\n",getChmod("/etc/passwd"));
    
        return 0;
    }
    

提交回复
热议问题