Reputation: 143
I have some trouble understanding the arguments in the open function, specifically used in the context of creating an output file. I do not quite understand the roles of flags and file permissions (the 2nd and 3rd arguments in the function). For instance, if I have the file permission 00200 (user has write permission), and the flag O_RDONLY (Read only), then can I read the file or write the file?
Upvotes: 1
Views: 1295
Reputation: 41271
The signature of open
is as follows:
int open(const char *pathname, int flags, mode_t mode);
There are three sets of "permissions" at play: The permissions of the file itself, the flags, and the mode.
The permissions of the file itself (e.g. 00200 meaning only user can write) specify what the operating system allows a program to do.
When you specify the flags, you indicate what you want to do with the file. For example, if the file is readonly to you (e.g. rwxr-xr-x
and you're not the owner), you will be allowed to open the file with O_RDONLY
. If you attempt to open the file with O_RDWR
or O_WRONLY
, you will receive an EPERM
(operation not permitted) error in errno
.
The mode
parameter is only relevant when you create a new file, such as when you open a file that doesn't exist1 and the flag O_CREAT
is specified. The file is created on the filesystem and its permissions are given by mode & ~umask
(see man 2 umask
for more details).
1 Of course, the containing directory must exist and you must have write+exec permissions on that directory.
Upvotes: 3