next up previous contents Back to Operating Systems Home Page
Next: Opening files Up: Block-oriented I/O in UNIX Previous: Block-oriented I/O in UNIX

File creation

Files are created with the creat() system call, declared as

int creat(const char *path, mode_t auth);
which takes in path the file name and in auth a specification of the access authorization the file should be created with. To understand this last item remember that UNIX enforces ownership of files by users or groups of users. Specifically, users own the files they create, are organized in groups, and can decide if and how users of their group, or of the rest of the user community, should access the files themselves. Three types of access permissions are defined: the owner of a file (or, more precisely, of the directory the file's in) can grant or revoke each of the access modes to each of three categories of users:

File permission are conveniently encoded by a 9 bit maskgif, of which the upper three bits are the flags for the user's permission, in the rwx order, the middle three are flags for the group permissions, and the lower three for the world. So, for example, if a file is created with a permission mask of 110 100 100, then the owner can read and write it, while the group and the rest of the world can only read it. For short, we can say that this files's permissions are ``rw-r-r-'', the dash meaning that the corresponding permission is denied. The binary file permission mask, which is obviously an integer number, is passed to creat() in its auth argument. Since binary number are not explicitly represented in C, the mask is usually in the form of an octal number, so to make clear what the permission for the various user categories are. You can easily obtain the octal equivalent of a mask by grouping the bits in triplets, and converting each triplet to decimal: the octal mask for the above example would then be 0644, and as you can see there is one digit per category of users (the leading zero is of course used only to indicate that this integer constant is an octal number).

The following example shows a file creation with rwxr-xr-x permissions; note also the dealing with error conditions in the standard way.

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

int fildes;
...
fildes=creat("myfile", 0755);
if (fildes==-1)
{
    perror("myfile");
    exit(1);
}
...

Note that creat() erases the content of the file whose creation is requested, if it already exists, and in this case the permissions are left unchanged.


next up previous contents Back to Operating Systems Home Page
Next: Opening files Up: Block-oriented I/O in UNIX Previous: Block-oriented I/O in UNIX

Franco Callari