I opened a file in C and wrote it with this code:

int fd = open("soandso.txt", O_RDWR | O_CREAT);
write(fd, buf_of_data, 3);

The file now has write permission only for me and that is not what I specified in open. What am I doing wrong?

  • Please paste the output of ls -l soandso.txt . Also, if there is some more code than you've shown, please paste it using some pastebin service. – schaiba Sep 22 '16 at 12:35
  • This is the only file manipulation code. – user190346 Sep 22 '16 at 16:22

File creation permissions are modified by the umask value.

So, for example:

$ umask
$ touch xyz
$ ls -l xyz
-rw-r--r-- 1 sweh sweh 0 Sep 22 08:37 xyz

The umask value matches the standard rwx pattern, and so a value of 0022 removes ----w--w- permissions from the newly created file.

We can change this:

$ umask 002
$ touch abc
$ ls -l abc
-rw-rw-r-- 1 sweh sweh 0 Sep 22 08:38 abc

Now the 002 mask only removes -------w-

To create files with no masking

$ umask 0
$ touch def
$ ls -l def
-rw-rw-rw- 1 sweh sweh 0 Sep 22 08:40 def

If you want your program to ignore the umask value then you must explicitly call the umask(2) function before calling open(2)

Note that when using open(2) with the O_CREAT flag then you should also pass a permission mode. eg


In this case the mode field is also modified via the umask value so the actual mode of the creation is (mode & ~umask).

| improve this answer | |
  • "then you must explicitly call the umask(2) function" ... or pass the mode as argument 3 to the open() call. – Patrick Sep 22 '16 at 12:45
  • @Patrick umask modifies the mode value as well in this case. – Stephen Harris Sep 22 '16 at 12:50
  • Hence why I said "or". Though I would argue that passing the mode is the proper method. Especially considering if you want to set bits, such as those >= 01000, or the executable bits. Neither of which the umask method will handle. – Patrick Sep 22 '16 at 15:08
  • @Patrick if you do open("foo",O_RDWR|O_CREAT,0666) and have a umask of 022 then the resulting file will still be 0644. If you want want to create a 666 file then you must clear the umask first. If you don't need to create it 0666 then you can chmod() the file after creation. – Stephen Harris Sep 22 '16 at 15:25
  • 1
    @MarkYisri You need to do both; the manpage for open(2) says that you must specify a mode value when using O_CREAT. And you need to ensure the umask matches what you want to ensure the result is what you want. – Stephen Harris Sep 22 '16 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy