Name
creat - Creates a new file or overwrites an existing one.
Syntax
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
int creat(pathname, pmode)
char *pathname;
int pmode;
Description
The creat function either creates a new file, or opens and
truncates an existing file. If the file specified by
pathname does not exist, a new file is created with the
given permission setting and is opened for writing. If the
file already exists and its permission setting allows
writing, creat truncates the file to length 0, destroying
the previous contents, and opens it for writing.
The permission setting, pmode, applies to newly created
files only. The new file receives the specified permission
setting, after it is closed for the first time. The integer
expression pmode contains one or both of the manifest
constants S_IWRITE and S_IREAD, defined in sys/stat.h. When
both constants are given, they are joined with the bitwise-
OR operator ( | ). The meaning of the pmode argument is as
follows:
Value Meaning
S_IWRITE Writing permitted
S_IREAD Reading permitted
S_IREAD | S_IWRITE Reading and writing permitted
If write permission is not given, then the file is read-
only. Under DOS and OS/2, it is not possible to give write-
only permission. Thus, the S_IWRITE and S_IREAD | S_IWRITE
modes are equivalent. Under DOS Versions 3.0 and later,
files opened using creat are always opened in compatibility
mode. (See sopen.)
The creat function applies the current file-permission mask
to pmode before setting the permissions. (See umask.)
Return Value
If successful, creat returns a handle for the created file.
Otherwise, it returns -1 and sets errno to one of the
following constants:
Value Meaning
EACCES Path name specifies an existing read-only file
or specifies a directory instead of a file
EMFILE No more handles available (too many open files)
ENOENT Path name not found
See Also
chmod(DOS), chsize(S), close(S), dup(S), dup2(S), open(DOS),
sopen(DOS), umask(DOS)
Notes
The creat routine is provided primarily for compatibility
with previous libraries. A call to open with O_CREAT and
O_TRUNC values specified in the oflag argument is equivalent
to creat and is preferable for new code.
Example
#include <sys/types.h> #include <sys/stat.h> #include <io.h>
#include <stdio.h> #include <stdlib.h>
main( ) {
int fh;
fh = creat("data",S_IREAD|S_IWRITE);
if (fh == -1)
perror("Couldn't create data file");
else
printf("Created data file.\n"); }
This program uses creat to create the file (or truncate the
existing file) named data and open it for writing.
(printed 6/18/89)