2

I'm using the open system call to both create and open a file in the following manner:

fileID = open("aFile", O_CREAT|O_RDWR|O_TRUNC);

I expect the file to be created with read and write permissions, and sometimes it is, but only times when I run ls -l I see just w, or just r, or just x, or ws, or rwx, etc. If I run my program with the system call 3 times, I may get 3 different file permissions set for aFile each time. I don't know what could be causing the problem since it seems to be being set randomly. Any ideas as to what may be the cause?

Bluasul
  • 325
  • 1
  • 3
  • 14
  • are you using a network drive? or local drive? – Jean-François Fabre Sep 07 '20 at 18:37
  • 1
    You have to specify the access mode. `int open(const char *pathname, int flags, mode_t mode);` "The mode argument specifies the file mode bits be applied when a new file is created. This argument must be supplied when O_CREAT or O_TMPFILE is specified in flags; if neither O_CREAT nor O_TMPFILE is specified, then mode is ignored." If you don't specify the mode, it may be a random value (undefined behavior). – Bodo Sep 07 '20 at 18:38

1 Answers1

4

open() takes a third argument which takes effect when creating a file. This argument is a set of flags that modify the access mode of the new file. If you don't set a value for this argument, the open() function will be provided with whatever happens to be in the register or stack position that applies to this argument -- depending on the specific system and compiler. In any case, it's unlikely to be what you intend, and will depend in an unpredictable way on the preceding code.

On Unix-like systems, man 2 open should give you all the details.

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15