Files: open/read/write/close (Overview)#

open()#

Swiss army knife: multiple actions, governed by bitwise-or’ed flags:

  • Create/Open/Truncate/…

  • Access intention (“mode”): open for reading, writing, both

  • Hundreds of others

#include <fcntl.h>

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

open() Flags#

Access Mode

  • O_RDONLY: Can only read(); error on write()

  • O_WRONLY: Can only write(); error on read()

  • O_RDWR: …

Creating a File

  • O_CREAT: create if not exists, else simply open

  • O_CREAT|O_EXCL: exclusive creation

    • error if file exists

    • ⟶ to prevent race conditions when two parties try to create a file at the smae time

    • security measure

Miscellaneous

  • O_APPEND: write access appends at the end

  • O_TRUNC: truncate file to zero length if already exists

  • O_CLOEXEC: exec() closes the file descriptor (⟶ later)

read()#

#include <unistd.h>

ssize_t read(int fd, void *buf, size_t count);
  • Return value: number of bytes read (-1 on error, as always)

  • 0 is End of File (EOF)

  • Can read less than count (usually with network I/O)

write()#

#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t count);
  • Return value: number of bytes written (-1 on error, as always)

  • Can write less than count (usually with network I/O)

  • SIGPIPE (process termination) when …

    • Writing to a network connection that has been closed by peer

    • Writing to a pipe where receiver end has closed/exited (hence SIGPIPE)