Opens a file for reading, writing, or editing. It positions the file at its beginning (byte 0).
#include <fcntl.h> int open (const char *file_spec, int flags, mode_t mode); (ANSI C) int open (const char *file_spec, int flags, . . . ); (DEC C Extension)
O_RDONLY | Open for reading only |
O_WRONLY | Open for writing only |
O_RDWR | Open for reading and writing |
O_NDELAY | Open for asynchronous input |
O_ APPEND | Append on each write |
O_CREAT | Create a file if it does not exist |
O_TRUNC | Create a new version of this file |
O_EXCL | Error if attempting to create existing file |
These flags are set using the bitwise OR operator (|) to separate specified flags. Opening a file with O_APPEND causes each write on the file to be appended to the end. If O_TRUNC is specified and the file exists, open creates a new file by incrementing the version number by 1, leaving the old version in existence.
If O_CREAT is set and the named file does not exist, the DEC C RTL creates it with any attributes specified in the fourth and subsequent arguments ( . . . ). If O_ EXCL is set with O_CREAT and the named file exists, the attempted open returns an error.
You can construct modes by using the bitwise OR operator (|) to separate specified modes. The modes are:
0400 | OWNER:READ |
0200 | OWNER:WRITE |
0100 | OWNER:EXECUTE |
0040 | GROUP:READ |
0020 | GROUP:WRITE |
0010 | GROUP:EXECUTE |
0004 | WORLD:READ |
0002 | WORLD:WRITE |
0001 | WORLD:EXECUTE |
The system is given the same access privileges as the owner. A WRITE privilege also implies a DELETE privilege.
See also creat, read, write, close, dup, dup2, and lseek in this section.
x | A nonnegative file descriptor number. |
-1 | Indicates that the file does not exist, that it is protected against reading or writing, or that it cannot be opened for another reason. |
#include <unixio.h> #include <file.h> main() { int file,stat; int flags; flags = O_RDWR ; /* Open for read and write, * with user default file protection, * with a maximum fixed record size of 2048 bytes, * and a block size 2048 bytes. */ file = open("file.dat",flags,0,"rfm=fix","mrs=2048","bls=2048"); if (file == -1) perror ("OPEN error"), exit(1); close (file); }