Opening Files

Name:
open()
System call or function: System call Links: Online Manual | Course Packet
What it does: Opens an existing file, or creates a new file and opens it.
What libraries you must include:
#include <sys/stat.h> // Defines modes such as S_IRUSR
#include <fcntl.h> // Defines open() and flags such as O_RDONLY
Syntax:
int open (const char *name, int flags, mode_t mode);
Description of arguments:
name
: double-quoted name of the file
flags
: what to do with the file, e.g.,: O_RDONLY, O_WRONLY, O_RDWR, O_APPEND, O_CREAT (O_EXCL), O_TRUNC.
mode
: If
flags
contains O_CREAT, sets default file permissions, e.g.,: S_IRWXU (owner: read, write, and execute), S_IRUSR (owner: read), S_IRGRP (group: read), S_IROTH (others: read), etc.
What type it returns:
int
On success: A legit file descriptor (a non-negative integer)
On failure:
-1
If failure, does it set
errno
?
Yes
Quick example:
int file_fd = open ("text.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR);
Other variations:
creat()