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

心不动则不痛 提交于 2019-12-01 19:45:30
Sinkingpoint

The permission bits can be ascertained using the st_mode field of the struct returned by the stat function. The individual bits can be extracted using the constants S_IRUSR (User Read), S_IWUSR (User Write), S_IRGRP (Group Read) etc.

Example:

struct stat statRes;
if(stat(file, &statRes) < 0)return 1;
mode_t bits = statRes.st_mode;
if((bits & S_IRUSR) == 0){
    //User doesn't have read privilages
}

In terms of passing this to chmod, mode_t is just a typedef of a uint_32, so that should be simple enough.

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

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>


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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!