open (C System Call)
open is a system call that is used to open a new file and obtain its file descriptor.
Required Include Files
#include <fcntl.h> /* Not technically required, but needed on some UNIX distributions */ #include <sys/types.h> #include <sys/stat.h>
Function Definition
int open(const char *path, int oflags); int open(const char *path, int oflags, mode_t mode);
| Field | Description |
|---|---|
| const char *path | The relative or absolute path to the file that is to be opened. |
| int oflags | A bitwise 'or' separated list of values that determine the method in which the file is to be opened (whether it should be read only, read/write, whether it should be cleared when opened, etc). See a list of legal values for this field at the end. |
| mode_t mode | A bitwise 'or' separated list of values that determine the permissions of the file if it is created. See a list of legal values at the end. |
| return value | Returns the file descriptor for the new file. The file descriptor returned is always the smallest integer greater than zero that is still available. If a negative value is returned, then there was an error opening the file. |
Code Snippet
Example using the open system call:
#include <unistd.h> #include <fcntl.h> int main() { size_t filedesc = open("testfile.txt", O_WRONLY | O_CREAT); if(filedesc < 0) return 1; if(write(filedesc,"This will be output to testfile.txt\n", 36) != 36) { write(2,"There was an error writing to testfile.txt\n",43); return 1; } return 0; }
Available Values for oflag
| Value | Meaning |
|---|---|
| O_RDONLY | Open the file so that it is read only. |
| O_WRONLY | Open the file so that it is write only. |
| O_RDWR | Open the file so that it can be read from and written to. |
| O_APPEND | Append new information to the end of the file. |
| O_TRUNC | Initially clear all data from the file. |
| O_CREAT | If the file does not exist, create it. If the O_CREAT option is used, then you must include the third parameter. |
| O_EXCL | Combined with the O_CREAT option, it ensures that the caller must create the file. If the file already exists, the call will fail. |
Available Values for mode
| Value | Meaning |
|---|---|
| S_IRUSR | Set read rights for the owner to true. |
| S_IWUSR | Set write rights for the owner to true. |
| S_IXUSR | Set execution rights for the owner to true. |
| S_IRGRP | Set read rights for the group to true. |
| S_IWGRP | Set write rights for the group to true. |
| S_IXGRP | Set execution rights for the group to true. |
| S_IROTH | Set read rights for other users to true. |
| S_IWOTH | Set write rights for other users to true. |
| S_IXOTH | Set execution rights for other users to true. |
page revision: 38, last edited: 04 Oct 2024 19:44





