C POSIX library |
---|
fcntl.h is the header in the C POSIX library for the C programming language that contains constructs for file control operations, e.g. opening a file, retrieving and changing the permissions of file, or locking a file for edit.
Contents |
int fcntl(int filedes, int cmd, ...)
cmd
on the file descriptor filedes
, with optional other arguments. cmd
can be any of the F_*
constants listed below. The return value depends on the command issued.int open(const char *path, int oflag, ... )
path
, where oflag
is one of the O_*
constants listed below. Returns a new file descriptor.int creat(const char *path, mode_t mode)
path
with mode mode
. Equivalent to open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)
. As with open
, returns the new file descriptor.The cmd
argument to fcntl
may be any of the following:
Constant | Description |
---|---|
F_DUPFD | duplicate file descriptor. |
F_GETFD | get file descriptor flags. |
F_SETFD | set file descriptor flags. |
F_GETFL | get file status flags and file access modes. |
F_SETFL | set file status flags. |
F_GETLK | get record locking information. |
F_SETLK | set record locking information. |
F_SETLKW | set record locking information; wait if blocked. |
F_GETOWN | get process or process group ID to receive SIGURG signals. |
F_SETOWN | set process or process group ID to receive SIGURG signals. |
The oflag
argument to open
must specify exactly one of the following:
Constant | Description |
---|---|
O_RDONLY | open for reading only. |
O_WRONLY | ppen for writing only. |
O_RDWR | open for reading and writing. |
And any combination of:
Constant | Description |
---|---|
O_CREAT | create file if it does not exist. |
O_EXCL | exclusive use flag. |
O_NOCTTY | do not assign controlling terminal. |
O_TRUNC | truncate flag. |
O_APPEND | set append mode. |
O_NONBLOCK | non-blocking mode. |
O_RSYNC | synchronized read I/O operations. |
O_SYNC | write according to synchronized I/O file integrity completion. |
fcntl.h
defines the struct flock
, which describes a file lock. It contains the following members:
short l_type /* type of lock, see below */ short l_whence /* starting offset */ off_t l_start /* relative offset in bytes */ off_t l_len /* size */ pid_t l_pid /* process of ID of lock holder */
l_type
is one of:
Constant | Description |
---|---|
F_RDLCK | shared or read lock. |
F_UNLCK | unlock. |
F_WRLCK | exclusive or write lock. |
A short example of fcntl.h usage is:
//C program using fcntl.h to get the size of a file. #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> int main(int argc, char** argv) { int fp; long int file_size; if (argc < 2) { fprintf(stderr, "Correct usage: %s <filename>\n", argv[0]); return 1; } if ((fp = open(argv[1], O_RDONLY)) == -1) { fprintf(stderr, "Error opening the file \n"); return 1; } file_size = filelength(fp); printf("The file size in is %ld bytes.\n", file_size); close(fp); return 0; }