Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.4 creat Function

A new file can also be created by

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>

    int creat(const char 
*pathname, mode_t mode); Returns: file descriptor
opened for write-only if OK,
-1 on error

Note that this function is equivalent to

    open (pathname, O_WRONLY | 
O_CREAT | O_TRUNC, mode);

In earlier versions of Unix the second argument to open could only be 0, 1, or 2. There was no way to open a file that didn't already exist. Therefore a separate system call, creat, was needed to create new files. With the O_CREAT and O_TRUNC options now provided by open, a separate creat function is no longer needed.

We'll show how to specify mode in Section 4.5 when we describe a file's access permissions in detail.

One deficiency with creat is that the file is opened only for writing. Before the new version of open was provided, if we were creating a temporary file that we wanted to write and then read back, we had to call creat, close, and then open. A better way is to use the new open function, as in

open (pathname, O_RDWR | O_CREAT | O_TRUNC, mode);
  • + Share This
  • 🔖 Save To Your Account