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

前端 未结 2 689
孤街浪徒
孤街浪徒 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:29

    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.

提交回复
热议问题