open()
: Opening Files#
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
#include <unistd.h>
int close(int fd);
Swiss Army Knife#
Swiss army knife: multiple actions, governed by bitwise-or’ed flags:
Create/Open/Truncate/…
flags
: access intention - open for reading, writing, appending, …Hundreds of others
⟶ man -s 2 open is a very hard read
open()
Flags#
Intended Access
O_RDONLY
: Can onlyread()
; error onwrite()
O_WRONLY
: Can onlywrite()
; error onread()
O_RDWR
: …
Creating a File
O_CREAT
: create if not exists, else simply openIf file is created,
mode
is used - file permissions
O_CREAT|O_EXCL
: exclusive creationerror if file exists
⟶ to prevent race conditions when two parties try to create a file at the same time
security measure
Miscellaneous
O_APPEND
: write access appends at the endO_TRUNC
: truncate file to zero length if already existsO_CLOEXEC
:exec()
closes the file descriptor (⟶ later)