Opening Files

Name:
creat()
System call or function: System call Links: Online Manual | Course Packet
What it does: Creates a new file and opens it for writing. If a file with the same name already exists, empty (truncate) it before opening it. Same as calling
open()
with the 3 flags:
O_WRONLY | O_CREAT | O_TRUNC
What libraries you must include:
#include <sys/stat.h> // Defines modes such as S_IRUSR
#include <fcntl.h> // Defines creat()
Syntax:
int creat (const char *name, mode_t mode);
Description of arguments:
name
: double-quoted name of the file
mode
: Sets default file permissions, e.g.,: S_IRWXU (owner: read, write, and execute), S_IRUSR (owner: read), S_IRGRP (group: read), S_IROTH (others: read), etc.
What type it returns:
int
On success: A legit file descriptor (a non-negative integer)
On failure:
-1
If failure, does it set
errno
?
Yes
Quick example:
int file_fd = creat ("text.txt", S_IWUSR | S_IRUSR | S_IXUSR);
Other variations:
open()