FAT | RFS | XFS | ZFS

open()

PROTOTYPE

#include <posix.h>

int open(const char *path, int oflag, ...);

DESCRIPTION

open() allocates a file control block and associates it with the file specified by path, optionally creating it. Paths starting with ‘/’ are absolute. Otherwise they are relative to the CWD. The current position is set to the beginning of the file, and its error and end-of-file flags are cleared.

oflag specifies the file mode and must include exactly one of the following:

  • O_RDONLY - Open for reading only
  • O_WRONLY - Open for writing only
  • O_RDWR - Open for both reading and writing

It may also include any of the following OR’d together with the above:

  • O_APPEND - sets the current position to the end of file before each file write
  • O_CREAT - creates the file. Requires a mode parameter like creat()
  • O_EXCL - fails if the file already exists. Only allowed if O_CREAT is set
  • O_TRUNC - truncates the file to zero length
  • O_DIRECT - allows cache bypassing (non-standard)
  • O_BUFFERED - enables asynchronous I/O buffering (non-standard)
  • O_NO_OVERWRITE - eliminates overwrites (TargetXFS only, non-standard)

If the file exists and is truncated, its status change and data modification timestamps are updated. If the file is created, every timestamp of the new file and the status change and data modification timestamps of its parent directory are updated. Its user and group IDs are set to those of the calling task (as determined by FsGetId()). A third parameter, which specifies the file’s access permission bits as modified by the file mode creation mask, is required for file creation.

The caller needs search access to the path prefix and either write access to the parent directory if a file is created or every file access requested by mode if the file exists.

If successful, open() returns a file descriptor, a small integer used by the other API routines to reference the file. Otherwise, it sets errno and returns -1.

ERROR CODES

EACCES No search access to the path prefix, file exists and a requested access is denied, or file is new and write access to parent directory is denied.
EEXIST O_CREAT and O_EXCL are both set and the specified file exists.
EFAULT path equals NULL.
EINVAL The leaf name in path is invalid.
EISDIR path refers to a directory and mode requires write access.
EMFILE No file control block is free. FOPEN_MAX files are currently open.
ENAMETOOLONG A name in path exceeds the effective maximum file name length.
ENOENT path is the empty string or includes file not found and not being created.
ENOSPC No space is left on volume to create file.
ENOTDIR One of the non-leaf path components is not a directory.
EROFS The volume is read-only and write, truncate, or create requested.

EXAMPLE

fn = open("/flash/log.txt", O_RDONLY);
if (fn == -1)
  perror("open() failed");