Unless we are using standard input and output, files need to be explicitly opened. open system call can be used to open a file and return a file descriptor. It returns -1 if any error occurs.
int open(char *name, int flags, mode_t perms);
The first argument, name, is a character string containing the filename. The second argument, flags, is an int that specifies how the file is to be opened; the main values are:
- O_RDONLY: Open for reading only.
- O_WRONLY: Open for writing only.
- O_RDWR: Open for both reading and writing.
These constants are defined in <fcntl.h>. We may OR the one of the above constants with the following optional constants:
- O_APPEND: Append to the end of file on each write.
- O_CREAT: Create the file if it doesn’t exist.
- O_EXCL: Generate an error if O_CREAT is also specified and the file already exists.
- O_TRUNC: If the file exists and it is successfully opened for either write-only or read-write, truncate its length to 0.
To open an existing file for reading, we could make this call:
fd = open(fname, O_RDONLY, 0);
We can also create a new file using creat system call.
int creat(char *name, mode_t perms);
It returns a file descriptor if it was able to create a file, else -1. If the file exists, creat will truncate its length to 0, thereby discarding its contents.
fd = creat(name, perms);
is equivalent to
fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, perms);
The perms argument (mode_t is an integer type) is used to specify permissions to the file being created. In UNIX file system, there are nine bits of permission information associated with a file that control read, write and execute access for the owner of the file, for the owner’s group, and for all others. Thus a three-digit octal number is convenient for specifying the permissions. For example, 0755 specifies read, write and execute permissions for the owner, and read and execute permissions for the group and others. An open file can be closed using close system call.
int close(int fd);
We need to pass the open file descriptor to close. It returns 0 if it was successful, -1 in case of any error.