This section describes the primitives for opening and closing files using file descriptors. The open
and creat
functions are declared in the header file `fcntl.h', while close
is declared in `unistd.h'.
open
function creates and returns a new file descriptor for the file named by filename. Initially, the file position indicator for the file is at the beginning of the file. The argument mode is used only when a file is created, but it doesn't hurt to supply the argument in any case. The flags argument controls how the file is to be opened. This is a bit mask; you create the value by the bitwise OR of the appropriate parameters (using the `|' operator in C). See File Status Flags, for the parameters available.
The normal return value from open
is a non-negative integer file descriptor. In the case of an error, a value of -1
is returned instead. In addition to the usual file name syntax errors (see File Name Errors), the following errno
error conditions are defined for this function:
EACCES
EEXIST
O_CREAT
and O_EXCL
are set, and the named file already exists.
EINTR
open
operation was interrupted by a signal. See Interrupted Primitives.
EISDIR
EMFILE
ENFILE
ENOENT
O_CREAT
is not specified.
ENOSPC
ENXIO
O_NONBLOCK
and O_WRONLY
are both set in the flags argument, the file named by filename is a FIFO (see Pipes and FIFOs), and no process has the file open for reading.
EROFS
O_WRONLY
, O_RDWR
, and O_TRUNC
are set in the flags argument, or O_CREAT
is set and the file does not already exist.
The open
function is the underlying primitive for the fopen
and freopen
functions, that create streams.
creat (filename, mode)
is equivalent to:
open (filename, O_WRONLY | O_CREAT | O_TRUNC, mode)
close
closes the file descriptor filedes. Closing a file has the following consequences:
The file descriptor is deallocated.
Any record locks owned by the process on the file are unlocked.
When all file descriptors associated with a pipe or FIFO have been closed, any unread data is discarded.
The normal return value from close
is 0
; a value of -1
is returned in case of failure. The following errno
error conditions are defined for this function:
EBADF
EINTR
close
call was interrupted by a signal. See Interrupted Primitives. Here is an example of how to handle EINTR
properly:
TEMP_FAILURE_RETRY (close (desc));
To close a stream, call fclose
(see Closing Streams) instead of trying to close its underlying file descriptor with close
. This flushes any buffered output and updates the stream object to indicate that it is closed.