How can I read linux file permission programmatically instead using \"ls\" then parse the result.
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);
}
}