Search code examples
cfile-permissionsuser-permissions

open() command does not create file with right permissions


I want to run the open() command so that it creates a file if it doesn't exist. As far as the manual goes, you should run it with the O_CREAT flag which then requires an additional argument that specifies the permissions for the newly created file.

My problem is, that it doesn't give outfile the right permissions. When I run this code:

int get_fd_outfile(char *filename)
{
    int fd_outfile;

    fd_outfile = open(filename, O_RDWR | O_TRUNC | O_CREAT, 0666); // permissions right?
    if (fd_outfile == -1)
        pipex_error("Error: Could not open output file for writing");
    return (fd_outfile);
}

I get a file with the following permissions: -rw-r--r-- [...] outfile. But I want it to have read/write for user, group and others. Why doesn't the octal code 0666 create the right permissions? But the O_[...] flags do actually work...

Edit: Maybe it's because I'm on a Mac? I read something about that...


Solution

  • Take a look at your umask value, it also plays a role in this:

                  The effective mode is modified by the process's umask in
                  the usual way: in the absence of a default ACL, the mode
                  of the created file is (mode & ~umask).
    

    From https://www.man7.org/linux/man-pages/man2/open.2.html

    Or from man 2 open on a Mac:

         The oflag argument may indicate that the file is to be created if it does not exist (by specifying
         the O_CREAT flag).  In this case, open() and openat() require an additional argument mode_t mode; the
         file is created with mode mode as described in chmod(2) and modified by the process' umask value (see
         umask(2)).
    

    You can use the umask command to see your current value. This is what it looks like for me:

    $ umask
    0022
    

    That masks out the w for group and other, and matches what you're seeing. You can use the umask() system call to change it within the C program, temporarily, or chmod() the resulting file afterward.