open() - open or create a file for reading or writing
#include <fcntl.h>
int open (const char *path, int o_flag, ...)
The file name specified by path is opened for reading and/or writing as specified by the argument o_flag and the file descriptor returned to the calling process. The o_flag argument may indicate the file is to be created if it does not exist (by specifying the O_CREAT flag), and modified by the process' umask value (see umask(2)).
The o_flag is a bitwise inclusive OR of the values from the following two tables.
You must include one of the three values (file access modes) from the following table in the value of o_flag.
Symbol | Meaning |
---|---|
O_RDONLY | Open for reading only |
O_RDWR | Open for reading and writing |
O_WRONLY | Open for writing only |
You can specify any combination of the remaining flags.
Symbol | Meaning |
---|---|
O_APPEND | Append on each write |
O_CREAT | Create file if it does not exist |
O_EXCL | Error if create and file exists |
O_NOCTTY | Do not acquire as a controlling terminal |
O_NONBLOCK | Do not block on open |
O_TRUNC | Truncate size to 0 |
O_SYNC | Perform synchronous I/O operations |
When the file is opened with the O_CREAT flag set and it doesn't already exist, open(2) requires a third argument, which it treats as a mode of type mode_t. This argument specifies the mode of the newly-created file. (For a description of a mode see the reference page for chmod(2).)
Opening a file with O_APPEND set causes each write on the file to be appended to the end. If O_TRUNC is specified and the file exists, the file is truncated to zero length. If O_EXCL is set with O_CREAT and the file already exists, open(2) returns an error. This may be used to implement a simple exclusive access locking mechanism. If O_EXCL is set and the last component of the pathname is a symbolic link, open(2) will fail even if the symbolic link points to a non-existent name. If the O_NONBLOCK flag is specified and the open(2) call would result in the process being blocked for some reason (e.g., waiting for carrier on a dialup line), open(2) returns immediately. The first time the process attempts to perform I/O on the open file it will block (not currently implemented).
If successful, open(2) returns a non-negative integer, termed a file descriptor. It returns -1 on failure. The file pointer used to mark the current position within the file is set to the beginning of the file.
When a new file is created it is given the group of the directory which contains it.
The new descriptor is set to remain open across execve(1) system calls; see close(2) and fcntl(2).
The system imposes a limit on the number of file descriptors open simultaneously by one process.
On success, the open(2) call returns an integer file descriptor which refers to the file. On failure, the call returns -1 and sets errno
The named file is opened unless:
chmod(2)
close(2)
creat(2)
dup(2)
fcntl(2)
lseek(2)
read(2)
write(2)
umask(2)