Search code examples
cunixposixfile-permissions

How to match open and stat mode_t?


I'm creating a file with open and setting its permissions, then I get the file permissions using stat....the permissions don't match. The result of the program below is:

mode from open (600) and stat (100600) are different



How can I compare the mode(permissions) set by open(2) and retrieved with stat(2)?

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

#include <fcntl.h>
#include <stdio.h>


int
main(int argc, char **argv, char **env) {
        
        const char *path = "/tmp/test";
        const mode_t mode = S_IRUSR | S_IWUSR;
        
        if (open(path, O_RDWR |  O_CREAT | O_EXCL, mode) == -1)
                err(1, "open for '%s' failed", path);
        
        struct stat sb;
        if (stat(path, &sb) != 0)
                err(2, "stat failed");
        
        if (mode != sb.st_mode)
                printf("mode from open (%o) and stat (%o) are different\n", 
                        mode, sb.st_mode);

        return 0;
}

Thanks


Solution

  • After upvoting user3477950's answer and comment which lead me to the answer; I'm answering my own question with code.

    The key part is sb.st_mode & RWX_UGO

    So, I ended up with something like:

    #define RWX_UGO (S_IRWXU | S_IRWXG | S_IRWXO)
    //....
    const mode_t file_mode = sb.st_mode & RWX_UGO;
    if (mode == file_mode)
            printf("file_mode (%o) & RWX_UGO(%o) equals to(%o) which is "
                        "equal to mode(%o)\n", sb.st_mode, RWX_UGO, 
                        file_mode, file_mode);
    else
            printf("mode from open (%o) and stat (%o) are different\n", 
                        mode, file_mode);
    


    which now prints

    file_mode (100600) & RWX_UGO(777) equals to(600) which is equal to mode(600)