How to read linux file permission programmatically in C/C++

前端 未结 2 584
慢半拍i
慢半拍i 2021-01-01 18:32

How can I read linux file permission programmatically instead using \"ls\" then parse the result.

2条回答
  •  灰色年华
    2021-01-01 18:37

    This is a function in C, that returns file permissions in the string format "rwxr-r--"

    char* permissions(char *file){
        struct stat st;
        char *modeval = malloc(sizeof(char) * 9 + 1);
        if(stat(file, &st) == 0){
            mode_t perm = st.st_mode;
            modeval[0] = (perm & S_IRUSR) ? 'r' : '-';
            modeval[1] = (perm & S_IWUSR) ? 'w' : '-';
            modeval[2] = (perm & S_IXUSR) ? 'x' : '-';
            modeval[3] = (perm & S_IRGRP) ? 'r' : '-';
            modeval[4] = (perm & S_IWGRP) ? 'w' : '-';
            modeval[5] = (perm & S_IXGRP) ? 'x' : '-';
            modeval[6] = (perm & S_IROTH) ? 'r' : '-';
            modeval[7] = (perm & S_IWOTH) ? 'w' : '-';
            modeval[8] = (perm & S_IXOTH) ? 'x' : '-';
            modeval[9] = '\0';
            return modeval;     
        }
        else{
            return strerror(errno);
        }   
    }
    

提交回复
热议问题