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()(see Reading Files)O_WRONLY: can onlywrite(); error onread()(see Writing Files)O_RDWR: both
Creating a File (see Creating Files)
O_CREAT: create if not exists, else simply openIf file is created,
modeis 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: closes the file descriptor onexec()(⟶ later)