ptg10805159
66 File I/O Chapter 3
3.4 creatFunction
Anew file can also be created by calling thecreatfunction.
#include <fcntl.h>
int creat(const char *path,mode_tmode);
Returns: file descriptor opened for write-only if OK,−1 on error
Note that this function is equivalent to
open(path,O_WRONLY | O_CREAT | O_TRUNC,mode);
Historically, in early versions of the UNIX System, the second argument toopencould be only
0, 1, or 2. Therewas no way toopenafile that didn’t already exist. Therefore, a separate
system call,creat,was needed to create new files.With theO_CREATandO_TRUNCoptions
now provided byopen,aseparatecreatfunction 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 withcreatis that the file is opened only for writing. Beforethe
new version ofopenwas provided, if we werecreating a temporary file that we wanted
to write and then read back, we had to callcreat,close,and thenopen.Abetter
way is to use theopenfunction, as in
open(path,O_RDWR | O_CREAT | O_TRUNC, mode);
3.5 closeFunction
An open file is closed by calling theclosefunction.
#include <unistd.h>
int close(intfd);
Returns: 0 if OK,−1 on error
Closing a file also releases any recordlocks that the process may have on the file. We’ll
discuss this point further in Section 14.3.
When a process terminates, all of its open files areclosed automatically by the
kernel. Many programs take advantage of this fact and don’t explicitly close open files.
See the program in Figure1.4, for example.
3.6 lseekFunction
Every open file has an associated ‘‘current file offset,’’normally a non-negative integer
that measures the number of bytes from the beginning of the file. (We describe some
exceptions to the ‘‘non-negative’’qualifier later in this section.) Read and write
operations normally start at the current file offset and cause the offset to be incremented
by the number of bytes read or written. By default, this offset is initialized to 0 when a
file is opened, unless theO_APPENDoption is specified.