Opening a File for Writing by the Owner
The following example opens the file /tmp/file
, either by
creating it (if it does not already exist), or by truncating its
length to 0 (if it does exist). In the former case, if the call
creates a new file, the access permission bits in the file mode
of the file are set to permit reading and writing by the owner,
and to permit reading only by group members and others.
If the call to open() is successful, the file is opened for
writing.
#include <fcntl.h>
...
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *pathname = "/tmp/file";
...
fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);
...
Opening a File Using an Existence Check
The following example uses the open() function to try to create
the LOCKFILE
file and open it for writing. Since the open()
function specifies the O_EXCL flag, the call fails if the file
already exists. In that case, the program assumes that someone
else is updating the password file and exits.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define LOCKFILE "/etc/ptmp"
...
int pfd; /* Integer for file descriptor returned by open() call. */
...
if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
exit(1);
}
...
Opening a File for Writing
The following example opens a file for writing, creating the file
if it does not already exist. If the file does exist, the system
truncates the file to zero bytes.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define LOCKFILE "/etc/ptmp"
...
int pfd;
char pathname[PATH_MAX+1];
...
if ((pfd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
perror("Cannot open output file\n"); exit(1);
}
...