Mon Dec 18 13:40:37 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu>
[glibc.git] / manual / filesys.texi
blobd2afe8623ff5c6dd6753557e4b52947d809deaad
1 @node File System Interface, Pipes and FIFOs, Low-Level I/O, Top
2 @chapter File System Interface
4 This chapter describes the GNU C library's functions for manipulating
5 files.  Unlike the input and output functions described in
6 @ref{I/O on Streams} and @ref{Low-Level I/O}, these
7 functions are concerned with operating on the files themselves, rather
8 than on their contents.
10 Among the facilities described in this chapter are functions for
11 examining or modifying directories, functions for renaming and deleting
12 files, and functions for examining and setting file attributes such as
13 access permissions and modification times.
15 @menu
16 * Working Directory::           This is used to resolve relative
17                                  file names.
18 * Accessing Directories::       Finding out what files a directory
19                                  contains.
20 * Hard Links::                  Adding alternate names to a file.
21 * Symbolic Links::              A file that ``points to'' a file name.
22 * Deleting Files::              How to delete a file, and what that means.
23 * Renaming Files::              Changing a file's name.
24 * Creating Directories::        A system call just for creating a directory.
25 * File Attributes::             Attributes of individual files.
26 * Making Special Files::        How to create special files.
27 * Temporary Files::             Naming and creating temporary files.
28 @end menu
30 @node Working Directory
31 @section Working Directory
33 @cindex current working directory
34 @cindex working directory
35 @cindex change working directory
36 Each process has associated with it a directory, called its @dfn{current
37 working directory} or simply @dfn{working directory}, that is used in
38 the resolution of relative file names (@pxref{File Name Resolution}).
40 When you log in and begin a new session, your working directory is
41 initially set to the home directory associated with your login account
42 in the system user database.  You can find any user's home directory
43 using the @code{getpwuid} or @code{getpwnam} functions; see @ref{User
44 Database}.
46 Users can change the working directory using shell commands like
47 @code{cd}.  The functions described in this section are the primitives
48 used by those commands and by other programs for examining and changing
49 the working directory.
50 @pindex cd
52 Prototypes for these functions are declared in the header file
53 @file{unistd.h}.
54 @pindex unistd.h
56 @comment unistd.h
57 @comment POSIX.1
58 @deftypefun {char *} getcwd (char *@var{buffer}, size_t @var{size})
59 The @code{getcwd} function returns an absolute file name representing
60 the current working directory, storing it in the character array
61 @var{buffer} that you provide.  The @var{size} argument is how you tell
62 the system the allocation size of @var{buffer}.
64 The GNU library version of this function also permits you to specify a
65 null pointer for the @var{buffer} argument.  Then @code{getcwd}
66 allocates a buffer automatically, as with @code{malloc}
67 (@pxref{Unconstrained Allocation}).  If the @var{size} is greater than
68 zero, then the buffer is that large; otherwise, the buffer is as large
69 as necessary to hold the result.
71 The return value is @var{buffer} on success and a null pointer on failure.
72 The following @code{errno} error conditions are defined for this function:
74 @table @code
75 @item EINVAL
76 The @var{size} argument is zero and @var{buffer} is not a null pointer.
78 @item ERANGE
79 The @var{size} argument is less than the length of the working directory
80 name.  You need to allocate a bigger array and try again.
82 @item EACCES
83 Permission to read or search a component of the file name was denied.
84 @end table
85 @end deftypefun
87 Here is an example showing how you could implement the behavior of GNU's
88 @w{@code{getcwd (NULL, 0)}} using only the standard behavior of
89 @code{getcwd}:
91 @smallexample
92 char *
93 gnu_getcwd ()
95   int size = 100;
96   char *buffer = (char *) xmalloc (size);
98   while (1)
99     @{
100       char *value = getcwd (buffer, size);
101       if (value != 0)
102         return buffer;
103       size *= 2;
104       free (buffer);
105       buffer = (char *) xmalloc (size);
106     @}
108 @end smallexample
110 @noindent
111 @xref{Malloc Examples}, for information about @code{xmalloc}, which is
112 not a library function but is a customary name used in most GNU
113 software.
115 @comment unistd.h
116 @comment BSD
117 @deftypefun {char *} getwd (char *@var{buffer})
118 This is similar to @code{getcwd}, but has no way to specify the size of
119 the buffer.  The GNU library provides @code{getwd} only
120 for backwards compatibility with BSD.
122 The @var{buffer} argument should be a pointer to an array at least
123 @code{PATH_MAX} bytes long (@pxref{Limits for Files}).  In the GNU
124 system there is no limit to the size of a file name, so this is not
125 necessarily enough space to contain the directory name.  That is why
126 this function is deprecated.
127 @end deftypefun
129 @comment unistd.h
130 @comment POSIX.1
131 @deftypefun int chdir (const char *@var{filename})
132 This function is used to set the process's working directory to
133 @var{filename}.
135 The normal, successful return value from @code{chdir} is @code{0}.  A
136 value of @code{-1} is returned to indicate an error.  The @code{errno}
137 error conditions defined for this function are the usual file name
138 syntax errors (@pxref{File Name Errors}), plus @code{ENOTDIR} if the
139 file @var{filename} is not a directory.
140 @end deftypefun
143 @node Accessing Directories
144 @section Accessing Directories
145 @cindex accessing directories
146 @cindex reading from a directory
147 @cindex directories, accessing
149 The facilities described in this section let you read the contents of a
150 directory file.  This is useful if you want your program to list all the
151 files in a directory, perhaps as part of a menu.
153 @cindex directory stream
154 The @code{opendir} function opens a @dfn{directory stream} whose
155 elements are directory entries.  You use the @code{readdir} function on
156 the directory stream to retrieve these entries, represented as
157 @w{@code{struct dirent}} objects.  The name of the file for each entry is
158 stored in the @code{d_name} member of this structure.  There are obvious
159 parallels here to the stream facilities for ordinary files, described in
160 @ref{I/O on Streams}.
162 @menu
163 * Directory Entries::           Format of one directory entry.
164 * Opening a Directory::         How to open a directory stream.
165 * Reading/Closing Directory::   How to read directory entries from the stream.
166 * Simple Directory Lister::     A very simple directory listing program.
167 * Random Access Directory::     Rereading part of the directory
168                                  already read with the same stream.
169 @end menu
171 @node Directory Entries
172 @subsection Format of a Directory Entry
174 @pindex dirent.h
175 This section describes what you find in a single directory entry, as you
176 might obtain it from a directory stream.  All the symbols are declared
177 in the header file @file{dirent.h}.
179 @comment dirent.h
180 @comment POSIX.1
181 @deftp {Data Type} {struct dirent}
182 This is a structure type used to return information about directory
183 entries.  It contains the following fields:
185 @table @code
186 @item char d_name[]
187 This is the null-terminated file name component.  This is the only
188 field you can count on in all POSIX systems.
190 @item ino_t d_fileno
191 This is the file serial number.  For BSD compatibility, you can also
192 refer to this member as @code{d_ino}.  In the GNU system and most POSIX
193 systems, for most files this the same as the @code{st_ino} member that
194 @code{stat} will return for the file.  @xref{File Attributes}.
196 @item unsigned char d_namlen
197 This is the length of the file name, not including the terminating null
198 character.  Its type is @code{unsigned char} because that is the integer
199 type of the appropriate size
201 @item unsigned char d_type
202 This is the type of the file, possibly unknown.  The following constants
203 are defined for its value:
205 @table @code
206 @item DT_UNKNOWN
207 The type is unknown.  On some systems this is the only value returned.
209 @item DT_REG
210 A regular file.
212 @item DT_DIR
213 A directory.
215 @item DT_FIFO
216 A named pipe, or FIFO.  @xref{FIFO Special Files}.
218 @item DT_SOCK
219 A local-domain socket.  @c !!! @xref{Local Domain}.
221 @item DT_CHR
222 A character device.
224 @item DT_BLK
225 A block device.
226 @end table
228 This member is a BSD extension.  Each value except DT_UNKNOWN
229 corresponds to the file type bits in the @code{st_mode} member of
230 @code{struct statbuf}.  These two macros convert between @code{d_type}
231 values and @code{st_mode} values:
233 @deftypefun int IFTODT (mode_t @var{mode})
234 This returns the @code{d_type} value corresponding to @var{mode}.
235 @end deftypefun
237 @deftypefun mode_t DTTOIF (int @var{dirtype})
238 This returns the @code{st_mode} value corresponding to @var{dirtype}.
239 @end deftypefun
240 @end table
242 This structure may contain additional members in the future.
244 When a file has multiple names, each name has its own directory entry.
245 The only way you can tell that the directory entries belong to a
246 single file is that they have the same value for the @code{d_fileno}
247 field.
249 File attributes such as size, modification times, and the like are part
250 of the file itself, not any particular directory entry.  @xref{File
251 Attributes}.
252 @end deftp
254 @node Opening a Directory
255 @subsection Opening a Directory Stream
257 @pindex dirent.h
258 This section describes how to open a directory stream.  All the symbols
259 are declared in the header file @file{dirent.h}.
261 @comment dirent.h
262 @comment POSIX.1
263 @deftp {Data Type} DIR
264 The @code{DIR} data type represents a directory stream.  
265 @end deftp
267 You shouldn't ever allocate objects of the @code{struct dirent} or
268 @code{DIR} data types, since the directory access functions do that for
269 you.  Instead, you refer to these objects using the pointers returned by
270 the following functions.
272 @comment dirent.h
273 @comment POSIX.1
274 @deftypefun {DIR *} opendir (const char *@var{dirname})
275 The @code{opendir} function opens and returns a directory stream for
276 reading the directory whose file name is @var{dirname}.  The stream has
277 type @code{DIR *}.
279 If unsuccessful, @code{opendir} returns a null pointer.  In addition to
280 the usual file name errors (@pxref{File Name Errors}), the
281 following @code{errno} error conditions are defined for this function:
283 @table @code
284 @item EACCES
285 Read permission is denied for the directory named by @code{dirname}.
287 @item EMFILE
288 The process has too many files open.
290 @item ENFILE
291 The entire system, or perhaps the file system which contains the
292 directory, cannot support any additional open files at the moment.
293 (This problem cannot happen on the GNU system.)
294 @end table
296 The @code{DIR} type is typically implemented using a file descriptor,
297 and the @code{opendir} function in terms of the @code{open} function.
298 @xref{Low-Level I/O}.  Directory streams and the underlying
299 file descriptors are closed on @code{exec} (@pxref{Executing a File}).
300 @end deftypefun
302 @node Reading/Closing Directory
303 @subsection Reading and Closing a Directory Stream
305 @pindex dirent.h
306 This section describes how to read directory entries from a directory
307 stream, and how to close the stream when you are done with it.  All the
308 symbols are declared in the header file @file{dirent.h}.
310 @comment dirent.h
311 @comment POSIX.1
312 @deftypefun {struct dirent *} readdir (DIR *@var{dirstream})
313 This function reads the next entry from the directory.  It normally
314 returns a pointer to a structure containing information about the file.
315 This structure is statically allocated and can be rewritten by a
316 subsequent call.
318 @strong{Portability Note:} On some systems, @code{readdir} may not
319 return entries for @file{.} and @file{..}, even though these are always
320 valid file names in any directory.  @xref{File Name Resolution}.
322 If there are no more entries in the directory or an error is detected,
323 @code{readdir} returns a null pointer.  The following @code{errno} error
324 conditions are defined for this function:
326 @table @code
327 @item EBADF
328 The @var{dirstream} argument is not valid.
329 @end table
330 @end deftypefun
332 @comment dirent.h
333 @comment POSIX.1
334 @deftypefun int closedir (DIR *@var{dirstream})
335 This function closes the directory stream @var{dirstream}.  It returns
336 @code{0} on success and @code{-1} on failure.  
338 The following @code{errno} error conditions are defined for this
339 function:
341 @table @code
342 @item EBADF
343 The @var{dirstream} argument is not valid.
344 @end table
345 @end deftypefun
347 @node Simple Directory Lister
348 @subsection Simple Program to List a Directory
350 Here's a simple program that prints the names of the files in
351 the current working directory:
353 @smallexample
354 @include dir.c.texi
355 @end smallexample
357 The order in which files appear in a directory tends to be fairly
358 random.  A more useful program would sort the entries (perhaps by
359 alphabetizing them) before printing them; see @ref{Array Sort Function}.
361 @c ??? not documented: scandir, alphasort
363 @node Random Access Directory
364 @subsection Random Access in a Directory Stream
366 @pindex dirent.h
367 This section describes how to reread parts of a directory that you have
368 already read from an open directory stream.  All the symbols are
369 declared in the header file @file{dirent.h}.
371 @comment dirent.h
372 @comment POSIX.1
373 @deftypefun void rewinddir (DIR *@var{dirstream})
374 The @code{rewinddir} function is used to reinitialize the directory
375 stream @var{dirstream}, so that if you call @code{readdir} it
376 returns information about the first entry in the directory again.  This
377 function also notices if files have been added or removed to the
378 directory since it was opened with @code{opendir}.  (Entries for these
379 files might or might not be returned by @code{readdir} if they were
380 added or removed since you last called @code{opendir} or
381 @code{rewinddir}.)
382 @end deftypefun
384 @comment dirent.h
385 @comment BSD
386 @deftypefun off_t telldir (DIR *@var{dirstream})
387 The @code{telldir} function returns the file position of the directory
388 stream @var{dirstream}.  You can use this value with @code{seekdir} to
389 restore the directory stream to that position.
390 @end deftypefun
392 @comment dirent.h
393 @comment BSD
394 @deftypefun void seekdir (DIR *@var{dirstream}, off_t @var{pos})
395 The @code{seekdir} function sets the file position of the directory
396 stream @var{dirstream} to @var{pos}.  The value @var{pos} must be the
397 result of a previous call to @code{telldir} on this particular stream;
398 closing and reopening the directory can invalidate values returned by
399 @code{telldir}.
400 @end deftypefun
402 @node Hard Links
403 @section Hard Links
404 @cindex hard link
405 @cindex link, hard
406 @cindex multiple names for one file
407 @cindex file names, multiple
409 In POSIX systems, one file can have many names at the same time.  All of
410 the names are equally real, and no one of them is preferred to the
411 others.
413 To add a name to a file, use the @code{link} function.  (The new name is
414 also called a @dfn{hard link} to the file.)  Creating a new link to a
415 file does not copy the contents of the file; it simply makes a new name
416 by which the file can be known, in addition to the file's existing name
417 or names.
419 One file can have names in several directories, so the the organization
420 of the file system is not a strict hierarchy or tree.
422 In most implementations, it is not possible to have hard links to the
423 same file in multiple file systems.  @code{link} reports an error if you
424 try to make a hard link to the file from another file system when this
425 cannot be done.
427 The prototype for the @code{link} function is declared in the header
428 file @file{unistd.h}.
429 @pindex unistd.h
431 @comment unistd.h
432 @comment POSIX.1
433 @deftypefun int link (const char *@var{oldname}, const char *@var{newname})
434 The @code{link} function makes a new link to the existing file named by
435 @var{oldname}, under the new name @var{newname}.
437 This function returns a value of @code{0} if it is successful and
438 @code{-1} on failure.  In addition to the usual file name errors
439 (@pxref{File Name Errors}) for both @var{oldname} and @var{newname}, the
440 following @code{errno} error conditions are defined for this function:
442 @table @code
443 @item EACCES
444 You are not allowed to write the directory in which the new link is to
445 be written.
446 @ignore 
447 Some implementations also require that the existing file be accessible
448 by the caller, and use this error to report failure for that reason.
449 @end ignore
451 @item EEXIST
452 There is already a file named @var{newname}.  If you want to replace
453 this link with a new link, you must remove the old link explicitly first.
455 @item EMLINK
456 There are already too many links to the file named by @var{oldname}.
457 (The maximum number of links to a file is @w{@code{LINK_MAX}}; see
458 @ref{Limits for Files}.)
460 @item ENOENT
461 The file named by @var{oldname} doesn't exist.  You can't make a link to
462 a file that doesn't exist.
464 @item ENOSPC
465 The directory or file system that would contain the new link is full
466 and cannot be extended.
468 @item EPERM
469 In the GNU system and some others, you cannot make links to directories.
470 Many systems allow only privileged users to do so.  This error
471 is used to report the problem.
473 @item EROFS
474 The directory containing the new link can't be modified because it's on
475 a read-only file system.
477 @item EXDEV
478 The directory specified in @var{newname} is on a different file system
479 than the existing file.
481 @item EIO
482 A hardware error occurred while trying to read or write the to filesystem.
483 @end table
484 @end deftypefun
486 @node Symbolic Links
487 @section Symbolic Links
488 @cindex soft link
489 @cindex link, soft
490 @cindex symbolic link
491 @cindex link, symbolic
493 The GNU system supports @dfn{soft links} or @dfn{symbolic links}.  This
494 is a kind of ``file'' that is essentially a pointer to another file
495 name.  Unlike hard links, symbolic links can be made to directories or
496 across file systems with no restrictions.  You can also make a symbolic
497 link to a name which is not the name of any file.  (Opening this link
498 will fail until a file by that name is created.)  Likewise, if the
499 symbolic link points to an existing file which is later deleted, the
500 symbolic link continues to point to the same file name even though the
501 name no longer names any file.
503 The reason symbolic links work the way they do is that special things
504 happen when you try to open the link.  The @code{open} function realizes
505 you have specified the name of a link, reads the file name contained in
506 the link, and opens that file name instead.  The @code{stat} function
507 likewise operates on the file that the symbolic link points to, instead
508 of on the link itself.
510 By contrast, other operations such as deleting or renaming the file
511 operate on the link itself.  The functions @code{readlink} and
512 @code{lstat} also refrain from following symbolic links, because their
513 purpose is to obtain information about the link.  So does @code{link},
514 the function that makes a hard link---it makes a hard link to the
515 symbolic link, which one rarely wants.
517 Prototypes for the functions listed in this section are in
518 @file{unistd.h}.
519 @pindex unistd.h
521 @comment unistd.h
522 @comment BSD
523 @deftypefun int symlink (const char *@var{oldname}, const char *@var{newname})
524 The @code{symlink} function makes a symbolic link to @var{oldname} named
525 @var{newname}.
527 The normal return value from @code{symlink} is @code{0}.  A return value
528 of @code{-1} indicates an error.  In addition to the usual file name
529 syntax errors (@pxref{File Name Errors}), the following @code{errno}
530 error conditions are defined for this function:
532 @table @code
533 @item EEXIST
534 There is already an existing file named @var{newname}.
536 @item EROFS
537 The file @var{newname} would exist on a read-only file system.
539 @item ENOSPC
540 The directory or file system cannot be extended to make the new link.
542 @item EIO
543 A hardware error occurred while reading or writing data on the disk.
545 @ignore
546 @comment not sure about these
547 @item ELOOP
548 There are too many levels of indirection.  This can be the result of
549 circular symbolic links to directories.
551 @item EDQUOT
552 The new link can't be created because the user's disk quota has been
553 exceeded.
554 @end ignore
555 @end table
556 @end deftypefun
558 @comment unistd.h
559 @comment BSD
560 @deftypefun int readlink (const char *@var{filename}, char *@var{buffer}, size_t @var{size})
561 The @code{readlink} function gets the value of the symbolic link
562 @var{filename}.  The file name that the link points to is copied into
563 @var{buffer}.  This file name string is @emph{not} null-terminated;
564 @code{readlink} normally returns the number of characters copied.  The
565 @var{size} argument specifies the maximum number of characters to copy,
566 usually the allocation size of @var{buffer}.
568 If the return value equals @var{size}, you cannot tell whether or not
569 there was room to return the entire name.  So make a bigger buffer and
570 call @code{readlink} again.  Here is an example:
572 @smallexample
573 char *
574 readlink_malloc (char *filename)
576   int size = 100;
578   while (1)
579     @{
580       char *buffer = (char *) xmalloc (size);
581       int nchars = readlink (filename, buffer, size);
582       if (nchars < size)
583         return buffer;
584       free (buffer);
585       size *= 2;
586     @}
588 @end smallexample
590 @c @group  Invalid outside example.
591 A value of @code{-1} is returned in case of error.  In addition to the
592 usual file name errors (@pxref{File Name Errors}), the following
593 @code{errno} error conditions are defined for this function:
595 @table @code
596 @item EINVAL
597 The named file is not a symbolic link.
599 @item EIO
600 A hardware error occurred while reading or writing data on the disk.
601 @end table
602 @c @end group
603 @end deftypefun
605 @node Deleting Files
606 @section Deleting Files
607 @cindex deleting a file
608 @cindex removing a file
609 @cindex unlinking a file
611 You can delete a file with the functions @code{unlink} or @code{remove}.
613 Deletion actually deletes a file name.  If this is the file's only name,
614 then the file is deleted as well.  If the file has other names as well
615 (@pxref{Hard Links}), it remains accessible under its other names.
617 @comment unistd.h
618 @comment POSIX.1
619 @deftypefun int unlink (const char *@var{filename})
620 The @code{unlink} function deletes the file name @var{filename}.  If
621 this is a file's sole name, the file itself is also deleted.  (Actually,
622 if any process has the file open when this happens, deletion is
623 postponed until all processes have closed the file.)
625 @pindex unistd.h
626 The function @code{unlink} is declared in the header file @file{unistd.h}.
628 This function returns @code{0} on successful completion, and @code{-1}
629 on error.  In addition to the usual file name errors
630 (@pxref{File Name Errors}), the following @code{errno} error conditions are 
631 defined for this function:
633 @table @code
634 @item EACCES
635 Write permission is denied for the directory from which the file is to be
636 removed, or the directory has the sticky bit set and you do not own the file.
638 @item EBUSY
639 This error indicates that the file is being used by the system in such a
640 way that it can't be unlinked.  For example, you might see this error if
641 the file name specifies the root directory or a mount point for a file
642 system.
644 @item ENOENT
645 The file name to be deleted doesn't exist.
647 @item EPERM
648 On some systems, @code{unlink} cannot be used to delete the name of a
649 directory, or can only be used this way by a privileged user.
650 To avoid such problems, use @code{rmdir} to delete directories.
651 (In the GNU system @code{unlink} can never delete the name of a directory.)
653 @item EROFS
654 The directory in which the file name is to be deleted is on a read-only
655 file system, and can't be modified.
656 @end table
657 @end deftypefun
659 @comment unistd.h
660 @comment POSIX.1
661 @deftypefun int rmdir (const char *@var{filename})
662 @cindex directories, deleting
663 @cindex deleting a directory
664 The @code{rmdir} function deletes a directory.  The directory must be
665 empty before it can be removed; in other words, it can only contain
666 entries for @file{.} and @file{..}.
668 In most other respects, @code{rmdir} behaves like @code{unlink}.  There
669 are two additional @code{errno} error conditions defined for
670 @code{rmdir}:
672 @table @code
673 @item ENOTEMPTY
674 @itemx EEXIST
675 The directory to be deleted is not empty.  
676 @end table
678 These two error codes are synonymous; some systems use one, and some use
679 the other.  The GNU system always uses @code{ENOTEMPTY}.
681 The prototype for this function is declared in the header file
682 @file{unistd.h}.
683 @pindex unistd.h
684 @end deftypefun
686 @comment stdio.h
687 @comment ANSI
688 @deftypefun int remove (const char *@var{filename})
689 This is the ANSI C function to remove a file.  It works like
690 @code{unlink} for files and like @code{rmdir} for directories.
691 @code{remove} is declared in @file{stdio.h}.
692 @pindex stdio.h
693 @end deftypefun
695 @node Renaming Files
696 @section Renaming Files
698 The @code{rename} function is used to change a file's name.
700 @cindex renaming a file
701 @comment stdio.h
702 @comment ANSI
703 @deftypefun int rename (const char *@var{oldname}, const char *@var{newname})
704 The @code{rename} function renames the file name @var{oldname} with
705 @var{newname}.  The file formerly accessible under the name
706 @var{oldname} is afterward accessible as @var{newname} instead.  (If the
707 file had any other names aside from @var{oldname}, it continues to have
708 those names.)
710 The directory containing the name @var{newname} must be on the same
711 file system as the file (as indicated by the name @var{oldname}).
713 One special case for @code{rename} is when @var{oldname} and
714 @var{newname} are two names for the same file.  The consistent way to
715 handle this case is to delete @var{oldname}.  However, POSIX requires
716 that in this case @code{rename} do nothing and report success---which is
717 inconsistent.  We don't know what your operating system will do.
719 If the @var{oldname} is not a directory, then any existing file named
720 @var{newname} is removed during the renaming operation.  However, if
721 @var{newname} is the name of a directory, @code{rename} fails in this
722 case.
724 If the @var{oldname} is a directory, then either @var{newname} must not
725 exist or it must name a directory that is empty.  In the latter case,
726 the existing directory named @var{newname} is deleted first.  The name
727 @var{newname} must not specify a subdirectory of the directory
728 @code{oldname} which is being renamed.
730 One useful feature of @code{rename} is that the meaning of the name
731 @var{newname} changes ``atomically'' from any previously existing file
732 by that name to its new meaning (the file that was called
733 @var{oldname}).  There is no instant at which @var{newname} is
734 nonexistent ``in between'' the old meaning and the new meaning.  If
735 there is a system crash during the operation, it is possible for both
736 names to still exist; but @var{newname} will always be intact if it
737 exists at all.
739 If @code{rename} fails, it returns @code{-1}.  In addition to the usual
740 file name errors (@pxref{File Name Errors}), the following
741 @code{errno} error conditions are defined for this function:
743 @table @code
744 @item EACCES
745 One of the directories containing @var{newname} or @var{oldname}
746 refuses write permission; or @var{newname} and @var{oldname} are
747 directories and write permission is refused for one of them.
749 @item EBUSY
750 A directory named by @var{oldname} or @var{newname} is being used by
751 the system in a way that prevents the renaming from working.  This includes
752 directories that are mount points for filesystems, and directories
753 that are the current working directories of processes.
755 @item ENOTEMPTY
756 @itemx EEXIST
757 The directory @var{newname} isn't empty.  The GNU system always returns
758 @code{ENOTEMPTY} for this, but some other systems return @code{EEXIST}.
760 @item EINVAL
761 The @var{oldname} is a directory that contains @var{newname}.
763 @item EISDIR
764 The @var{newname} names a directory, but the @var{oldname} doesn't.
766 @item EMLINK
767 The parent directory of @var{newname} would have too many links.
769 @item ENOENT
770 The file named by @var{oldname} doesn't exist.
772 @item ENOSPC
773 The directory that would contain @var{newname} has no room for another
774 entry, and there is no space left in the file system to expand it.
776 @item EROFS
777 The operation would involve writing to a directory on a read-only file
778 system.
780 @item EXDEV
781 The two file names @var{newname} and @var{oldnames} are on different
782 file systems.
783 @end table
784 @end deftypefun
786 @node Creating Directories
787 @section Creating Directories
788 @cindex creating a directory
789 @cindex directories, creating
791 @pindex mkdir
792 Directories are created with the @code{mkdir} function.  (There is also
793 a shell command @code{mkdir} which does the same thing.)
794 @c !!! umask
796 @comment sys/stat.h
797 @comment POSIX.1
798 @deftypefun int mkdir (const char *@var{filename}, mode_t @var{mode})
799 The @code{mkdir} function creates a new, empty directory whose name is
800 @var{filename}.
802 The argument @var{mode} specifies the file permissions for the new
803 directory file.  @xref{Permission Bits}, for more information about
804 this.
806 A return value of @code{0} indicates successful completion, and
807 @code{-1} indicates failure.  In addition to the usual file name syntax
808 errors (@pxref{File Name Errors}), the following @code{errno} error
809 conditions are defined for this function:
811 @table @code
812 @item EACCES
813 Write permission is denied for the parent directory in which the new
814 directory is to be added.
816 @item EEXIST
817 A file named @var{filename} already exists.
819 @item EMLINK
820 The parent directory has too many links.
822 Well-designed file systems never report this error, because they permit
823 more links than your disk could possibly hold.  However, you must still
824 take account of the possibility of this error, as it could result from
825 network access to a file system on another machine.
827 @item ENOSPC
828 The file system doesn't have enough room to create the new directory.
830 @item EROFS
831 The parent directory of the directory being created is on a read-only
832 file system, and cannot be modified.
833 @end table
835 To use this function, your program should include the header file
836 @file{sys/stat.h}.
837 @pindex sys/stat.h
838 @end deftypefun
840 @node File Attributes
841 @section File Attributes
843 @pindex ls
844 When you issue an @samp{ls -l} shell command on a file, it gives you
845 information about the size of the file, who owns it, when it was last
846 modified, and the like.  This kind of information is called the
847 @dfn{file attributes}; it is associated with the file itself and not a
848 particular one of its names.
850 This section contains information about how you can inquire about and
851 modify these attributes of files.
853 @menu
854 * Attribute Meanings::          The names of the file attributes, 
855                                  and what their values mean.
856 * Reading Attributes::          How to read the attributes of a file.
857 * Testing File Type::           Distinguishing ordinary files,
858                                  directories, links... 
859 * File Owner::                  How ownership for new files is determined,
860                                  and how to change it.
861 * Permission Bits::             How information about a file's access
862                                  mode is stored. 
863 * Access Permission::           How the system decides who can access a file.
864 * Setting Permissions::         How permissions for new files are assigned,
865                                  and how to change them.
866 * Testing File Access::         How to find out if your process can
867                                  access a file. 
868 * File Times::                  About the time attributes of a file.
869 @end menu
871 @node Attribute Meanings
872 @subsection What the File Attribute Values Mean
873 @cindex status of a file
874 @cindex attributes of a file
875 @cindex file attributes
877 When you read the attributes of a file, they come back in a structure
878 called @code{struct stat}.  This section describes the names of the
879 attributes, their data types, and what they mean.  For the functions
880 to read the attributes of a file, see @ref{Reading Attributes}.
882 The header file @file{sys/stat.h} declares all the symbols defined
883 in this section.
884 @pindex sys/stat.h
886 @comment sys/stat.h
887 @comment POSIX.1
888 @deftp {Data Type} {struct stat}
889 The @code{stat} structure type is used to return information about the
890 attributes of a file.  It contains at least the following members:
892 @table @code
893 @item mode_t st_mode
894 Specifies the mode of the file.  This includes file type information
895 (@pxref{Testing File Type}) and the file permission bits
896 (@pxref{Permission Bits}).
898 @item ino_t st_ino
899 The file serial number, which distinguishes this file from all other
900 files on the same device.
902 @item dev_t st_dev
903 Identifies the device containing the file.  The @code{st_ino} and
904 @code{st_dev}, taken together, uniquely identify the file.  The
905 @code{st_dev} value is not necessarily consistent across reboots or
906 system crashes, however.
908 @item nlink_t st_nlink
909 The number of hard links to the file.  This count keeps track of how
910 many directories have entries for this file.  If the count is ever
911 decremented to zero, then the file itself is discarded as soon as no
912 process still holds it open.  Symbolic links are not counted in the
913 total.
915 @item uid_t st_uid
916 The user ID of the file's owner.  @xref{File Owner}.
918 @item gid_t st_gid
919 The group ID of the file.  @xref{File Owner}.
921 @item off_t st_size
922 This specifies the size of a regular file in bytes.  For files that
923 are really devices and the like, this field isn't usually meaningful.
924 For symbolic links, this specifies the length of the file name the link
925 refers to.
927 @item time_t st_atime
928 This is the last access time for the file.  @xref{File Times}.
930 @item unsigned long int st_atime_usec
931 This is the fractional part of the last access time for the file.
932 @xref{File Times}.
934 @item time_t st_mtime
935 This is the time of the last modification to the contents of the file.
936 @xref{File Times}.
938 @item unsigned long int st_mtime_usec
939 This is the fractional part of the time of last modification to the
940 contents of the file.  @xref{File Times}.
942 @item time_t st_ctime
943 This is the time of the last modification to the attributes of the file.
944 @xref{File Times}.
946 @item unsigned long int st_ctime_usec
947 This is the fractional part of the time of last modification to the
948 attributes of the file.  @xref{File Times}.
950 @c !!! st_rdev
951 @item unsigned int st_blocks
952 This is the amount of disk space that the file occupies, measured in
953 units of 512-byte blocks.
955 The number of disk blocks is not strictly proportional to the size of
956 the file, for two reasons: the file system may use some blocks for
957 internal record keeping; and the file may be sparse---it may have
958 ``holes'' which contain zeros but do not actually take up space on the
959 disk.
961 You can tell (approximately) whether a file is sparse by comparing this
962 value with @code{st_size}, like this:
964 @smallexample
965 (st.st_blocks * 512 < st.st_size)
966 @end smallexample
968 This test is not perfect because a file that is just slightly sparse
969 might not be detected as sparse at all.  For practical applications,
970 this is not a problem.
972 @item unsigned int st_blksize
973 The optimal block size for reading of writing this file, in bytes.  You
974 might use this size for allocating the buffer space for reading of
975 writing the file.  (This is unrelated to @code{st_blocks}.)
976 @end table
977 @end deftp
979   Some of the file attributes have special data type names which exist
980 specifically for those attributes.  (They are all aliases for well-known
981 integer types that you know and love.)  These typedef names are defined
982 in the header file @file{sys/types.h} as well as in @file{sys/stat.h}.
983 Here is a list of them.
985 @comment sys/types.h
986 @comment POSIX.1
987 @deftp {Data Type} mode_t
988 This is an integer data type used to represent file modes.  In the
989 GNU system, this is equivalent to @code{unsigned int}.
990 @end deftp
992 @cindex inode number
993 @comment sys/types.h
994 @comment POSIX.1
995 @deftp {Data Type} ino_t
996 This is an arithmetic data type used to represent file serial numbers.
997 (In Unix jargon, these are sometimes called @dfn{inode numbers}.)
998 In the GNU system, this type is equivalent to @code{unsigned long int}.
999 @end deftp
1001 @comment sys/types.h
1002 @comment POSIX.1
1003 @deftp {Data Type} dev_t
1004 This is an arithmetic data type used to represent file device numbers.
1005 In the GNU system, this is equivalent to @code{int}.
1006 @end deftp
1008 @comment sys/types.h
1009 @comment POSIX.1
1010 @deftp {Data Type} nlink_t
1011 This is an arithmetic data type used to represent file link counts.
1012 In the GNU system, this is equivalent to @code{unsigned short int}.
1013 @end deftp
1015 @node Reading Attributes
1016 @subsection Reading the Attributes of a File
1018 To examine the attributes of files, use the functions @code{stat},
1019 @code{fstat} and @code{lstat}.  They return the attribute information in
1020 a @code{struct stat} object.  All three functions are declared in the
1021 header file @file{sys/stat.h}.
1023 @comment sys/stat.h
1024 @comment POSIX.1
1025 @deftypefun int stat (const char *@var{filename}, struct stat *@var{buf})
1026 The @code{stat} function returns information about the attributes of the
1027 file named by @w{@var{filename}} in the structure pointed at by @var{buf}.
1029 If @var{filename} is the name of a symbolic link, the attributes you get
1030 describe the file that the link points to.  If the link points to a
1031 nonexistent file name, then @code{stat} fails, reporting a nonexistent
1032 file.
1034 The return value is @code{0} if the operation is successful, and @code{-1}
1035 on failure.  In addition to the usual file name errors
1036 (@pxref{File Name Errors}, the following @code{errno} error conditions
1037 are defined for this function:
1039 @table @code
1040 @item ENOENT
1041 The file named by @var{filename} doesn't exist.
1042 @end table
1043 @end deftypefun
1045 @comment sys/stat.h
1046 @comment POSIX.1
1047 @deftypefun int fstat (int @var{filedes}, struct stat *@var{buf})
1048 The @code{fstat} function is like @code{stat}, except that it takes an
1049 open file descriptor as an argument instead of a file name.
1050 @xref{Low-Level I/O}.
1052 Like @code{stat}, @code{fstat} returns @code{0} on success and @code{-1}
1053 on failure.  The following @code{errno} error conditions are defined for
1054 @code{fstat}:
1056 @table @code
1057 @item EBADF
1058 The @var{filedes} argument is not a valid file descriptor.
1059 @end table
1060 @end deftypefun
1062 @comment sys/stat.h
1063 @comment BSD
1064 @deftypefun int lstat (const char *@var{filename}, struct stat *@var{buf})
1065 The @code{lstat} function is like @code{stat}, except that it does not
1066 follow symbolic links.  If @var{filename} is the name of a symbolic
1067 link, @code{lstat} returns information about the link itself; otherwise,
1068 @code{lstat} works like @code{stat}.  @xref{Symbolic Links}.
1069 @end deftypefun
1071 @node Testing File Type
1072 @subsection Testing the Type of a File
1074 The @dfn{file mode}, stored in the @code{st_mode} field of the file
1075 attributes, contains two kinds of information: the file type code, and
1076 the access permission bits.  This section discusses only the type code,
1077 which you can use to tell whether the file is a directory, whether it is
1078 a socket, and so on.  For information about the access permission,
1079 @ref{Permission Bits}.
1081 There are two predefined ways you can access the file type portion of
1082 the file mode.  First of all, for each type of file, there is a 
1083 @dfn{predicate macro} which examines a file mode value and returns
1084 true or false---is the file of that type, or not.  Secondly, you can
1085 mask out the rest of the file mode to get just a file type code.
1086 You can compare this against various constants for the supported file
1087 types.
1089 All of the symbols listed in this section are defined in the header file
1090 @file{sys/stat.h}.
1091 @pindex sys/stat.h
1093 The following predicate macros test the type of a file, given the value
1094 @var{m} which is the @code{st_mode} field returned by @code{stat} on
1095 that file:
1097 @comment sys/stat.h
1098 @comment POSIX
1099 @deftypefn Macro int S_ISDIR (mode_t @var{m})
1100 This macro returns nonzero if the file is a directory.
1101 @end deftypefn
1103 @comment sys/stat.h
1104 @comment POSIX
1105 @deftypefn Macro int S_ISCHR (mode_t @var{m})
1106 This macro returns nonzero if the file is a character special file (a
1107 device like a terminal).
1108 @end deftypefn
1110 @comment sys/stat.h
1111 @comment POSIX
1112 @deftypefn Macro int S_ISBLK (mode_t @var{m})
1113 This macro returns nonzero if the file is a block special file (a device
1114 like a disk).
1115 @end deftypefn
1117 @comment sys/stat.h
1118 @comment POSIX
1119 @deftypefn Macro int S_ISREG (mode_t @var{m})
1120 This macro returns nonzero if the file is a regular file.
1121 @end deftypefn
1123 @comment sys/stat.h
1124 @comment POSIX
1125 @deftypefn Macro int S_ISFIFO (mode_t @var{m})
1126 This macro returns nonzero if the file is a FIFO special file, or a
1127 pipe.  @xref{Pipes and FIFOs}.
1128 @end deftypefn
1130 @comment sys/stat.h
1131 @comment GNU
1132 @deftypefn Macro int S_ISLNK (mode_t @var{m})
1133 This macro returns nonzero if the file is a symbolic link.
1134 @xref{Symbolic Links}.
1135 @end deftypefn
1137 @comment sys/stat.h
1138 @comment GNU
1139 @deftypefn Macro int S_ISSOCK (mode_t @var{m})
1140 This macro returns nonzero if the file is a socket.  @xref{Sockets}.
1141 @end deftypefn
1143 An alterate non-POSIX method of testing the file type is supported for
1144 compatibility with BSD.  The mode can be bitwise ANDed with
1145 @code{S_IFMT} to extract the file type code, and compared to the
1146 appropriate type code constant.  For example,
1148 @smallexample
1149 S_ISCHR (@var{mode})
1150 @end smallexample
1152 @noindent
1153 is equivalent to:
1155 @smallexample
1156 ((@var{mode} & S_IFMT) == S_IFCHR)
1157 @end smallexample
1159 @comment sys/stat.h
1160 @comment BSD
1161 @deftypevr Macro int S_IFMT
1162 This is a bit mask used to extract the file type code portion of a mode
1163 value.
1164 @end deftypevr
1166 These are the symbolic names for the different file type codes:
1168 @table @code
1169 @comment sys/stat.h
1170 @comment BSD
1171 @item S_IFDIR
1172 @vindex S_IFDIR
1173 This macro represents the value of the file type code for a directory file.
1175 @comment sys/stat.h
1176 @comment BSD
1177 @item S_IFCHR
1178 @vindex S_IFCHR
1179 This macro represents the value of the file type code for a
1180 character-oriented device file.
1182 @comment sys/stat.h
1183 @comment BSD
1184 @item S_IFBLK
1185 @vindex S_IFBLK
1186 This macro represents the value of the file type code for a block-oriented
1187 device file.
1189 @comment sys/stat.h
1190 @comment BSD
1191 @item S_IFREG
1192 @vindex S_IFREG
1193 This macro represents the value of the file type code for a regular file.
1195 @comment sys/stat.h
1196 @comment BSD
1197 @item S_IFLNK
1198 @vindex S_IFLNK
1199 This macro represents the value of the file type code for a symbolic link.
1201 @comment sys/stat.h
1202 @comment BSD
1203 @item S_IFSOCK
1204 @vindex S_IFSOCK
1205 This macro represents the value of the file type code for a socket.
1207 @comment sys/stat.h
1208 @comment BSD
1209 @item S_IFIFO
1210 @vindex S_IFIFO
1211 This macro represents the value of the file type code for a FIFO or pipe.
1212 @end table
1214 @node File Owner
1215 @subsection File Owner
1216 @cindex file owner
1217 @cindex owner of a file
1218 @cindex group owner of a file
1220 Every file has an @dfn{owner} which is one of the registered user names
1221 defined on the system.  Each file also has a @dfn{group}, which is one
1222 of the defined groups.  The file owner can often be useful for showing
1223 you who edited the file (especially when you edit with GNU Emacs), but
1224 its main purpose is for access control.
1226 The file owner and group play a role in determining access because the
1227 file has one set of access permission bits for the user that is the
1228 owner, another set that apply to users who belong to the file's group,
1229 and a third set of bits that apply to everyone else.  @xref{Access
1230 Permission}, for the details of how access is decided based on this
1231 data.
1233 When a file is created, its owner is set from the effective user ID of
1234 the process that creates it (@pxref{Process Persona}).  The file's group
1235 ID may be set from either effective group ID of the process, or the
1236 group ID of the directory that contains the file, depending on the
1237 system where the file is stored.  When you access a remote file system,
1238 it behaves according to its own rule, not according to the system your
1239 program is running on.  Thus, your program must be prepared to encounter
1240 either kind of behavior, no matter what kind of system you run it on.
1242 @pindex chown
1243 @pindex chgrp
1244 You can change the owner and/or group owner of an existing file using
1245 the @code{chown} function.  This is the primitive for the @code{chown}
1246 and @code{chgrp} shell commands.
1248 @pindex unistd.h
1249 The prototype for this function is declared in @file{unistd.h}.
1251 @comment unistd.h
1252 @comment POSIX.1
1253 @deftypefun int chown (const char *@var{filename}, uid_t @var{owner}, gid_t @var{group})
1254 The @code{chown} function changes the owner of the file @var{filename} to
1255 @var{owner}, and its group owner to @var{group}.
1257 Changing the owner of the file on certain systems clears the set-user-ID
1258 and set-group-ID bits of the file's permissions.  (This is because those
1259 bits may not be appropriate for the new owner.)  The other file
1260 permission bits are not changed.
1262 The return value is @code{0} on success and @code{-1} on failure.
1263 In addition to the usual file name errors (@pxref{File Name Errors}), 
1264 the following @code{errno} error conditions are defined for this function:
1266 @table @code
1267 @item EPERM
1268 This process lacks permission to make the requested change.
1270 Only privileged users or the file's owner can change the file's group.
1271 On most file systems, only privileged users can change the file owner;
1272 some file systems allow you to change the owner if you are currently the
1273 owner.  When you access a remote file system, the behavior you encounter
1274 is determined by the system that actually holds the file, not by the
1275 system your program is running on.
1277 @xref{Options for Files}, for information about the
1278 @code{_POSIX_CHOWN_RESTRICTED} macro.
1280 @item EROFS
1281 The file is on a read-only file system.
1282 @end table
1283 @end deftypefun
1285 @comment unistd.h
1286 @comment BSD
1287 @deftypefun int fchown (int @var{filedes}, int @var{owner}, int @var{group})
1288 This is like @code{chown}, except that it changes the owner of the file
1289 with open file descriptor @var{filedes}.
1291 The return value from @code{fchown} is @code{0} on success and @code{-1}
1292 on failure.  The following @code{errno} error codes are defined for this
1293 function:
1295 @table @code
1296 @item EBADF
1297 The @var{filedes} argument is not a valid file descriptor.
1299 @item EINVAL
1300 The @var{filedes} argument corresponds to a pipe or socket, not an ordinary
1301 file.
1303 @item EPERM
1304 This process lacks permission to make the requested change.  For
1305 details, see @code{chmod}, above.
1307 @item EROFS
1308 The file resides on a read-only file system.
1309 @end table
1310 @end deftypefun
1312 @node Permission Bits
1313 @subsection The Mode Bits for Access Permission
1315 The @dfn{file mode}, stored in the @code{st_mode} field of the file
1316 attributes, contains two kinds of information: the file type code, and
1317 the access permission bits.  This section discusses only the access
1318 permission bits, which control who can read or write the file.
1319 @xref{Testing File Type}, for information about the file type code.
1321 All of the symbols listed in this section are defined in the header file
1322 @file{sys/stat.h}.
1323 @pindex sys/stat.h
1325 @cindex file permission bits
1326 These symbolic constants are defined for the file mode bits that control
1327 access permission for the file:
1329 @table @code
1330 @comment sys/stat.h
1331 @comment POSIX.1
1332 @item S_IRUSR
1333 @vindex S_IRUSR
1334 @comment sys/stat.h
1335 @comment BSD
1336 @itemx S_IREAD
1337 @vindex S_IREAD
1338 Read permission bit for the owner of the file.  On many systems, this
1339 bit is 0400.  @code{S_IREAD} is an obsolete synonym provided for BSD
1340 compatibility.
1342 @comment sys/stat.h
1343 @comment POSIX.1
1344 @item S_IWUSR
1345 @vindex S_IWUSR
1346 @comment sys/stat.h
1347 @comment BSD
1348 @itemx S_IWRITE
1349 @vindex S_IWRITE
1350 Write permission bit for the owner of the file.  Usually 0200.
1351 @w{@code{S_IWRITE}} is an obsolete synonym provided for BSD compatibility.
1353 @comment sys/stat.h
1354 @comment POSIX.1
1355 @item S_IXUSR
1356 @vindex S_IXUSR
1357 @comment sys/stat.h
1358 @comment BSD
1359 @itemx S_IEXEC
1360 @vindex S_IEXEC
1361 Execute (for ordinary files) or search (for directories) permission bit
1362 for the owner of the file.  Usually 0100.  @code{S_IEXEC} is an obsolete
1363 synonym provided for BSD compatibility.
1365 @comment sys/stat.h
1366 @comment POSIX.1
1367 @item S_IRWXU
1368 @vindex S_IRWXU
1369 This is equivalent to @samp{(S_IRUSR | S_IWUSR | S_IXUSR)}.
1371 @comment sys/stat.h
1372 @comment POSIX.1
1373 @item S_IRGRP
1374 @vindex S_IRGRP
1375 Read permission bit for the group owner of the file.  Usually 040.
1377 @comment sys/stat.h
1378 @comment POSIX.1
1379 @item S_IWGRP
1380 @vindex S_IWGRP
1381 Write permission bit for the group owner of the file.  Usually 020.
1383 @comment sys/stat.h
1384 @comment POSIX.1
1385 @item S_IXGRP
1386 @vindex S_IXGRP
1387 Execute or search permission bit for the group owner of the file.
1388 Usually 010.
1390 @comment sys/stat.h
1391 @comment POSIX.1
1392 @item S_IRWXG
1393 @vindex S_IRWXG
1394 This is equivalent to @samp{(S_IRGRP | S_IWGRP | S_IXGRP)}.
1396 @comment sys/stat.h
1397 @comment POSIX.1
1398 @item S_IROTH
1399 @vindex S_IROTH
1400 Read permission bit for other users.  Usually 04.
1402 @comment sys/stat.h
1403 @comment POSIX.1
1404 @item S_IWOTH
1405 @vindex S_IWOTH
1406 Write permission bit for other users.  Usually 02.
1408 @comment sys/stat.h
1409 @comment POSIX.1
1410 @item S_IXOTH
1411 @vindex S_IXOTH
1412 Execute or search permission bit for other users.  Usually 01.
1414 @comment sys/stat.h
1415 @comment POSIX.1
1416 @item S_IRWXO
1417 @vindex S_IRWXO
1418 This is equivalent to @samp{(S_IROTH | S_IWOTH | S_IXOTH)}.
1420 @comment sys/stat.h
1421 @comment POSIX
1422 @item S_ISUID
1423 @vindex S_ISUID
1424 This is the set-user-ID on execute bit, usually 04000. 
1425 @xref{How Change Persona}.
1427 @comment sys/stat.h
1428 @comment POSIX
1429 @item S_ISGID
1430 @vindex S_ISGID
1431 This is the set-group-ID on execute bit, usually 02000.
1432 @xref{How Change Persona}.
1434 @cindex sticky bit
1435 @comment sys/stat.h
1436 @comment BSD
1437 @item S_ISVTX
1438 @vindex S_ISVTX
1439 This is the @dfn{sticky} bit, usually 01000.
1441 On a directory, it gives permission to delete a file in the directory
1442 only if you own that file.  Ordinarily, a user either can delete all the
1443 files in the directory or cannot delete any of them (based on whether
1444 the user has write permission for the directory).  The same restriction
1445 applies---you must both have write permission for the directory and own
1446 the file you want to delete.  The one exception is that the owner of the
1447 directory can delete any file in the directory, no matter who owns it
1448 (provided the owner has given himself write permission for the
1449 directory).  This is commonly used for the @file{/tmp} directory, where
1450 anyone may create files, but not delete files created by other users.
1452 Originally the sticky bit on an executable file modified the swapping
1453 policies of the system.  Normally, when a program terminated, its pages
1454 in core were immediately freed and reused.  If the sticky bit was set on
1455 the executable file, the system kept the pages in core for a while as if
1456 the program were still running.  This was advantageous for a program
1457 likely to be run many times in succession.  This usage is obsolete in
1458 modern systems.  When a program terminates, its pages always remain in
1459 core as long as there is no shortage of memory in the system.  When the
1460 program is next run, its pages will still be in core if no shortage
1461 arose since the last run.
1463 On some modern systems where the sticky bit has no useful meaning for an
1464 executable file, you cannot set the bit at all for a non-directory.
1465 If you try, @code{chmod} fails with @code{EFTYPE}; 
1466 @pxref{Setting Permissions}.
1468 Some systems (particularly SunOS) have yet another use for the sticky
1469 bit.  If the sticky bit is set on a file that is @emph{not} executable,
1470 it means the opposite: never cache the pages of this file at all.  The
1471 main use of this is for the files on an NFS server machine which are
1472 used as the swap area of diskless client machines.  The idea is that the
1473 pages of the file will be cached in the client's memory, so it is a
1474 waste of the server's memory to cache them a second time.  In this use
1475 the sticky bit also says that the filesystem may fail to record the
1476 file's modification time onto disk reliably (the idea being that noone
1477 cares for a swap file).
1478 @end table
1480 The actual bit values of the symbols are listed in the table above
1481 so you can decode file mode values when debugging your programs.
1482 These bit values are correct for most systems, but they are not
1483 guaranteed.
1485 @strong{Warning:} Writing explicit numbers for file permissions is bad
1486 practice.  It is not only nonportable, it also requires everyone who
1487 reads your program to remember what the bits mean.  To make your
1488 program clean, use the symbolic names.
1490 @node Access Permission
1491 @subsection How Your Access to a File is Decided
1492 @cindex permission to access a file
1493 @cindex access permission for a file
1494 @cindex file access permission
1496 Recall that the operating system normally decides access permission for
1497 a file based on the effective user and group IDs of the process, and its
1498 supplementary group IDs, together with the file's owner, group and
1499 permission bits.  These concepts are discussed in detail in
1500 @ref{Process Persona}.
1502 If the effective user ID of the process matches the owner user ID of the
1503 file, then permissions for read, write, and execute/search are
1504 controlled by the corresponding ``user'' (or ``owner'') bits.  Likewise,
1505 if any of the effective group ID or supplementary group IDs of the
1506 process matches the group owner ID of the file, then permissions are
1507 controlled by the ``group'' bits.  Otherwise, permissions are controlled
1508 by the ``other'' bits.
1510 Privileged users, like @samp{root}, can access any file, regardless of
1511 its file permission bits.  As a special case, for a file to be
1512 executable even for a privileged user, at least one of its execute bits
1513 must be set.
1515 @node Setting Permissions
1516 @subsection Assigning File Permissions
1518 @cindex file creation mask
1519 @cindex umask
1520 The primitive functions for creating files (for example, @code{open} or
1521 @code{mkdir}) take a @var{mode} argument, which specifies the file
1522 permissions for the newly created file.  But the specified mode is
1523 modified by the process's @dfn{file creation mask}, or @dfn{umask},
1524 before it is used.
1526 The bits that are set in the file creation mask identify permissions
1527 that are always to be disabled for newly created files.  For example, if
1528 you set all the ``other'' access bits in the mask, then newly created
1529 files are not accessible at all to processes in the ``other''
1530 category, even if the @var{mode} argument specified to the creation 
1531 function would permit such access.  In other words, the file creation
1532 mask is the complement of the ordinary access permissions you want to
1533 grant.
1535 Programs that create files typically specify a @var{mode} argument that
1536 includes all the permissions that make sense for the particular file.
1537 For an ordinary file, this is typically read and write permission for
1538 all classes of users.  These permissions are then restricted as
1539 specified by the individual user's own file creation mask.
1541 @findex chmod
1542 To change the permission of an existing file given its name, call
1543 @code{chmod}.  This function ignores the file creation mask; it uses
1544 exactly the specified permission bits.
1546 @pindex umask
1547 In normal use, the file creation mask is initialized in the user's login
1548 shell (using the @code{umask} shell command), and inherited by all
1549 subprocesses.  Application programs normally don't need to worry about
1550 the file creation mask.  It will do automatically what it is supposed to
1553 When your program should create a file and bypass the umask for its
1554 access permissions, the easiest way to do this is to use @code{fchmod}
1555 after opening the file, rather than changing the umask.
1557 In fact, changing the umask is usually done only by shells.  They use
1558 the @code{umask} function.
1560 The functions in this section are declared in @file{sys/stat.h}.
1561 @pindex sys/stat.h
1563 @comment sys/stat.h
1564 @comment POSIX.1
1565 @deftypefun mode_t umask (mode_t @var{mask})
1566 The @code{umask} function sets the file creation mask of the current
1567 process to @var{mask}, and returns the previous value of the file
1568 creation mask.
1570 Here is an example showing how to read the mask with @code{umask}
1571 without changing it permanently:
1573 @smallexample
1574 mode_t
1575 read_umask (void)
1577   mask = umask (0);
1578   umask (mask);
1580 @end smallexample
1582 @noindent
1583 However, it is better to use @code{getumask} if you just want to read
1584 the mask value, because that is reentrant (at least if you use the GNU
1585 operating system).
1586 @end deftypefun
1588 @comment sys/stat.h
1589 @comment GNU
1590 @deftypefun mode_t getumask (void)
1591 Return the current value of the file creation mask for the current
1592 process.  This function is a GNU extension.
1593 @end deftypefun
1595 @comment sys/stat.h
1596 @comment POSIX.1
1597 @deftypefun int chmod (const char *@var{filename}, mode_t @var{mode})
1598 The @code{chmod} function sets the access permission bits for the file
1599 named by @var{filename} to @var{mode}.
1601 If the @var{filename} names a symbolic link, @code{chmod} changes the
1602 permission of the file pointed to by the link, not those of the link
1603 itself.
1605 This function returns @code{0} if successful and @code{-1} if not.  In
1606 addition to the usual file name errors (@pxref{File Name
1607 Errors}), the following @code{errno} error conditions are defined for
1608 this function:
1610 @table @code
1611 @item ENOENT
1612 The named file doesn't exist.
1614 @item EPERM
1615 This process does not have permission to change the access permission of
1616 this file.  Only the file's owner (as judged by the effective user ID of
1617 the process) or a privileged user can change them.
1619 @item EROFS
1620 The file resides on a read-only file system.
1622 @item EFTYPE
1623 @var{mode} has the @code{S_ISVTX} bit (the ``sticky bit'') set,
1624 and the named file is not a directory.  Some systems do not allow setting the
1625 sticky bit on non-directory files, and some do (and only some of those
1626 assign a useful meaning to the bit for non-directory files).
1628 You only get @code{EFTYPE} on systems where the sticky bit has no useful
1629 meaning for non-directory files, so it is always safe to just clear the
1630 bit in @var{mode} and call @code{chmod} again.  @xref{Permission Bits},
1631 for full details on the sticky bit.
1632 @end table
1633 @end deftypefun
1635 @comment sys/stat.h
1636 @comment BSD
1637 @deftypefun int fchmod (int @var{filedes}, int @var{mode})
1638 This is like @code{chmod}, except that it changes the permissions of
1639 the file currently open via descriptor @var{filedes}.
1641 The return value from @code{fchmod} is @code{0} on success and @code{-1}
1642 on failure.  The following @code{errno} error codes are defined for this
1643 function:
1645 @table @code
1646 @item EBADF
1647 The @var{filedes} argument is not a valid file descriptor.
1649 @item EINVAL
1650 The @var{filedes} argument corresponds to a pipe or socket, or something
1651 else that doesn't really have access permissions.
1653 @item EPERM
1654 This process does not have permission to change the access permission of
1655 this file.  Only the file's owner (as judged by the effective user ID of
1656 the process) or a privileged user can change them.
1658 @item EROFS
1659 The file resides on a read-only file system.
1660 @end table
1661 @end deftypefun
1663 @node Testing File Access
1664 @subsection Testing Permission to Access a File
1665 @cindex testing access permission
1666 @cindex access, testing for
1667 @cindex setuid programs and file access
1669 When a program runs as a privileged user, this permits it to access
1670 files off-limits to ordinary users---for example, to modify
1671 @file{/etc/passwd}.  Programs designed to be run by ordinary users but
1672 access such files use the setuid bit feature so that they always run
1673 with @code{root} as the effective user ID.
1675 Such a program may also access files specified by the user, files which
1676 conceptually are being accessed explicitly by the user.  Since the
1677 program runs as @code{root}, it has permission to access whatever file
1678 the user specifies---but usually the desired behavior is to permit only
1679 those files which the user could ordinarily access.
1681 The program therefore must explicitly check whether @emph{the user}
1682 would have the necessary access to a file, before it reads or writes the
1683 file.
1685 To do this, use the function @code{access}, which checks for access
1686 permission based on the process's @emph{real} user ID rather than the
1687 effective user ID.  (The setuid feature does not alter the real user ID,
1688 so it reflects the user who actually ran the program.)
1690 There is another way you could check this access, which is easy to
1691 describe, but very hard to use.  This is to examine the file mode bits
1692 and mimic the system's own access computation.  This method is
1693 undesirable because many systems have additional access control
1694 features; your program cannot portably mimic them, and you would not
1695 want to try to keep track of the diverse features that different systems
1696 have.  Using @code{access} is simple and automatically does whatever is
1697 appropriate for the system you are using.
1699 @code{access} is @emph{only} only appropriate to use in setuid programs.
1700 A non-setuid program will always use the effective ID rather than the
1701 real ID.
1703 @pindex unistd.h
1704 The symbols in this section are declared in @file{unistd.h}.
1706 @comment unistd.h
1707 @comment POSIX.1
1708 @deftypefun int access (const char *@var{filename}, int @var{how})
1709 The @code{access} function checks to see whether the file named by
1710 @var{filename} can be accessed in the way specified by the @var{how}
1711 argument.  The @var{how} argument either can be the bitwise OR of the
1712 flags @code{R_OK}, @code{W_OK}, @code{X_OK}, or the existence test
1713 @code{F_OK}.
1715 This function uses the @emph{real} user and group ID's of the calling
1716 process, rather than the @emph{effective} ID's, to check for access
1717 permission.  As a result, if you use the function from a @code{setuid}
1718 or @code{setgid} program (@pxref{How Change Persona}), it gives
1719 information relative to the user who actually ran the program.
1721 The return value is @code{0} if the access is permitted, and @code{-1}
1722 otherwise.  (In other words, treated as a predicate function,
1723 @code{access} returns true if the requested access is @emph{denied}.)
1725 In addition to the usual file name errors (@pxref{File Name
1726 Errors}), the following @code{errno} error conditions are defined for
1727 this function:
1729 @table @code
1730 @item EACCES
1731 The access specified by @var{how} is denied.
1733 @item ENOENT
1734 The file doesn't exist.
1736 @item EROFS
1737 Write permission was requested for a file on a read-only file system.
1738 @end table
1739 @end deftypefun
1741 These macros are defined in the header file @file{unistd.h} for use
1742 as the @var{how} argument to the @code{access} function.  The values
1743 are integer constants.
1744 @pindex unistd.h
1746 @comment unistd.h
1747 @comment POSIX.1
1748 @deftypevr Macro int R_OK
1749 Argument that means, test for read permission.
1750 @end deftypevr
1752 @comment unistd.h
1753 @comment POSIX.1
1754 @deftypevr Macro int W_OK
1755 Argument that means, test for write permission.
1756 @end deftypevr
1758 @comment unistd.h
1759 @comment POSIX.1
1760 @deftypevr Macro int X_OK
1761 Argument that means, test for execute/search permission.
1762 @end deftypevr
1764 @comment unistd.h
1765 @comment POSIX.1
1766 @deftypevr Macro int F_OK
1767 Argument that means, test for existence of the file.
1768 @end deftypevr
1770 @node File Times
1771 @subsection File Times
1773 @cindex file access time
1774 @cindex file modification time
1775 @cindex file attribute modification time
1776 Each file has three timestamps associated with it:  its access time,
1777 its modification time, and its attribute modification time.  These
1778 correspond to the @code{st_atime}, @code{st_mtime}, and @code{st_ctime}
1779 members of the @code{stat} structure; see @ref{File Attributes}.  
1781 All of these times are represented in calendar time format, as
1782 @code{time_t} objects.  This data type is defined in @file{time.h}.
1783 For more information about representation and manipulation of time
1784 values, see @ref{Calendar Time}.
1785 @pindex time.h
1787 Reading from a file updates its access time attribute, and writing
1788 updates its modification time.  When a file is created, all three
1789 timestamps for that file are set to the current time.  In addition, the
1790 attribute change time and modification time fields of the directory that
1791 contains the new entry are updated.
1793 Adding a new name for a file with the @code{link} function updates the
1794 attribute change time field of the file being linked, and both the
1795 attribute change time and modification time fields of the directory
1796 containing the new name.  These same fields are affected if a file name
1797 is deleted with @code{unlink}, @code{remove}, or @code{rmdir}.  Renaming
1798 a file with @code{rename} affects only the attribute change time and
1799 modification time fields of the two parent directories involved, and not
1800 the times for the file being renamed.
1802 Changing attributes of a file (for example, with @code{chmod}) updates
1803 its attribute change time field.
1805 You can also change some of the timestamps of a file explicitly using
1806 the @code{utime} function---all except the attribute change time.  You
1807 need to include the header file @file{utime.h} to use this facility.
1808 @pindex utime.h
1810 @comment time.h
1811 @comment POSIX.1
1812 @deftp {Data Type} {struct utimbuf}
1813 The @code{utimbuf} structure is used with the @code{utime} function to
1814 specify new access and modification times for a file.  It contains the
1815 following members:
1817 @table @code
1818 @item time_t actime
1819 This is the access time for the file.
1821 @item time_t modtime
1822 This is the modification time for the file.
1823 @end table
1824 @end deftp
1826 @comment time.h
1827 @comment POSIX.1
1828 @deftypefun int utime (const char *@var{filename}, const struct utimbuf *@var{times})
1829 This function is used to modify the file times associated with the file
1830 named @var{filename}.
1832 If @var{times} is a null pointer, then the access and modification times
1833 of the file are set to the current time.  Otherwise, they are set to the
1834 values from the @code{actime} and @code{modtime} members (respectively)
1835 of the @code{utimbuf} structure pointed at by @var{times}.  
1837 The attribute modification time for the file is set to the current time
1838 in either case (since changing the timestamps is itself a modification
1839 of the file attributes).
1841 The @code{utime} function returns @code{0} if successful and @code{-1}
1842 on failure.  In addition to the usual file name errors
1843 (@pxref{File Name Errors}), the following @code{errno} error conditions
1844 are defined for this function:
1846 @table @code
1847 @item EACCES
1848 There is a permission problem in the case where a null pointer was
1849 passed as the @var{times} argument.  In order to update the timestamp on
1850 the file, you must either be the owner of the file, have write
1851 permission on the file, or be a privileged user.
1853 @item ENOENT
1854 The file doesn't exist.
1856 @item EPERM
1857 If the @var{times} argument is not a null pointer, you must either be
1858 the owner of the file or be a privileged user.  This error is used to
1859 report the problem.
1861 @item EROFS
1862 The file lives on a read-only file system.
1863 @end table
1864 @end deftypefun
1866 Each of the three time stamps has a corresponding microsecond part,
1867 which extends its resolution.  These fields are called
1868 @code{st_atime_usec}, @code{st_mtime_usec}, and @code{st_ctime_usec};
1869 each has a value between 0 and 999,999, which indicates the time in
1870 microseconds.  They correspond to the @code{tv_usec} field of a
1871 @code{timeval} structure; see @ref{High-Resolution Calendar}.
1873 The @code{utimes} function is like @code{utime}, but also lets you specify
1874 the fractional part of the file times.  The prototype for this function is
1875 in the header file @file{sys/time.h}.
1876 @pindex sys/time.h
1878 @comment sys/time.h
1879 @comment BSD
1880 @deftypefun int utimes (const char *@var{filename}, struct timeval @var{tvp}@t{[2]})
1881 This function sets the file access and modification times for the file
1882 named by @var{filename}.  The new file access time is specified by
1883 @code{@var{tvp}[0]}, and the new modification time by
1884 @code{@var{tvp}[1]}.  This function comes from BSD.
1886 The return values and error conditions are the same as for the @code{utime}
1887 function.
1888 @end deftypefun
1890 @node Making Special Files
1891 @section Making Special Files
1892 @cindex creating special files
1893 @cindex special files
1895 The @code{mknod} function is the primitive for making special files,
1896 such as files that correspond to devices.  The GNU library includes
1897 this function for compatibility with BSD.
1899 The prototype for @code{mknod} is declared in @file{sys/stat.h}.
1900 @pindex sys/stat.h
1902 @comment sys/stat.h
1903 @comment BSD
1904 @deftypefun int mknod (const char *@var{filename}, int @var{mode}, int @var{dev})
1905 The @code{mknod} function makes a special file with name @var{filename}.
1906 The @var{mode} specifies the mode of the file, and may include the various
1907 special file bits, such as @code{S_IFCHR} (for a character special file)
1908 or @code{S_IFBLK} (for a block special file).  @xref{Testing File Type}.
1910 The @var{dev} argument specifies which device the special file refers to.
1911 Its exact interpretation depends on the kind of special file being created.
1913 The return value is @code{0} on success and @code{-1} on error.  In addition
1914 to the usual file name errors (@pxref{File Name Errors}), the
1915 following @code{errno} error conditions are defined for this function:
1917 @table @code
1918 @item EPERM
1919 The calling process is not privileged.  Only the superuser can create
1920 special files.
1922 @item ENOSPC
1923 The directory or file system that would contain the new file is full
1924 and cannot be extended.
1926 @item EROFS
1927 The directory containing the new file can't be modified because it's on
1928 a read-only file system.
1930 @item EEXIST
1931 There is already a file named @var{filename}.  If you want to replace
1932 this file, you must remove the old file explicitly first.
1933 @end table
1934 @end deftypefun
1936 @node Temporary Files
1937 @section Temporary Files
1939 If you need to use a temporary file in your program, you can use the
1940 @code{tmpfile} function to open it.  Or you can use the @code{tmpnam}
1941 function make a name for a temporary file and then open it in the usual
1942 way with @code{fopen}.
1944 The @code{tempnam} function is like @code{tmpnam} but lets you choose
1945 what directory temporary files will go in, and something about what
1946 their file names will look like.
1948 These facilities are declared in the header file @file{stdio.h}.
1949 @pindex stdio.h
1951 @comment stdio.h
1952 @comment ANSI
1953 @deftypefun {FILE *} tmpfile (void)
1954 This function creates a temporary binary file for update mode, as if by
1955 calling @code{fopen} with mode @code{"wb+"}.  The file is deleted
1956 automatically when it is closed or when the program terminates.  (On
1957 some other ANSI C systems the file may fail to be deleted if the program
1958 terminates abnormally).
1959 @end deftypefun
1961 @comment stdio.h
1962 @comment ANSI
1963 @deftypefun {char *} tmpnam (char *@var{result})
1964 This function constructs and returns a file name that is a valid file
1965 name and that does not name any existing file.  If the @var{result}
1966 argument is a null pointer, the return value is a pointer to an internal
1967 static string, which might be modified by subsequent calls.  Otherwise,
1968 the @var{result} argument should be a pointer to an array of at least
1969 @code{L_tmpnam} characters, and the result is written into that array.
1971 It is possible for @code{tmpnam} to fail if you call it too many times.
1972 This is because the fixed length of a temporary file name gives room for
1973 only a finite number of different names.  If @code{tmpnam} fails, it
1974 returns a null pointer.
1975 @end deftypefun
1977 @comment stdio.h
1978 @comment ANSI
1979 @deftypevr Macro int L_tmpnam
1980 The value of this macro is an integer constant expression that represents
1981 the minimum allocation size of a string large enough to hold the
1982 file name generated by the @code{tmpnam} function.
1983 @end deftypevr
1985 @comment stdio.h
1986 @comment ANSI
1987 @deftypevr Macro int TMP_MAX
1988 The macro @code{TMP_MAX} is a lower bound for how many temporary names
1989 you can create with @code{tmpnam}.  You can rely on being able to call
1990 @code{tmpnam} at least this many times before it might fail saying you
1991 have made too many temporary file names.
1993 With the GNU library, you can create a very large number of temporary
1994 file names---if you actually create the files, you will probably run out
1995 of disk space before you run out of names.  Some other systems have a
1996 fixed, small limit on the number of temporary files.  The limit is never
1997 less than @code{25}.
1998 @end deftypevr
2000 @comment stdio.h
2001 @comment SVID
2002 @deftypefun {char *} tempnam (const char *@var{dir}, const char *@var{prefix})
2003 This function generates a unique temporary filename.  If @var{prefix} is
2004 not a null pointer, up to five characters of this string are used as a
2005 prefix for the file name.  The return value is a string newly allocated
2006 with @code{malloc}; you should release its storage with @code{free} when
2007 it is no longer needed.
2009 The directory prefix for the temporary file name is determined by testing
2010 each of the following, in sequence.  The directory must exist and be
2011 writable.
2013 @itemize @bullet
2014 @item
2015 The environment variable @code{TMPDIR}, if it is defined.
2017 @item
2018 The @var{dir} argument, if it is not a null pointer.
2020 @item
2021 The value of the @code{P_tmpdir} macro.
2023 @item
2024 The directory @file{/tmp}.
2025 @end itemize
2027 This function is defined for SVID compatibility.
2028 @end deftypefun
2029 @cindex TMPDIR environment variable
2031 @comment stdio.h
2032 @comment SVID
2033 @c !!! are we putting SVID/GNU/POSIX.1/BSD in here or not??
2034 @deftypevr {SVID Macro} {char *} P_tmpdir
2035 This macro is the name of the default directory for temporary files.
2036 @end deftypevr
2038 Older Unix systems did not have the functions just described.  Instead
2039 they used @code{mktemp} and @code{mkstemp}.  Both of these functions
2040 work by modifying a file name template string you pass.  The last six
2041 characters of this string must be @samp{XXXXXX}.  These six @samp{X}s
2042 are replaced with six characters which make the whole string a unique
2043 file name.  Usually the template string is something like
2044 @samp{/tmp/@var{prefix}XXXXXX}, and each program uses a unique @var{prefix}.
2046 @strong{Note:} Because @code{mktemp} and @code{mkstemp} modify the
2047 template string, you @emph{must not} pass string constants to them.
2048 String constants are normally in read-only storage, so your program
2049 would crash when @code{mktemp} or @code{mkstemp} tried to modify the
2050 string.
2052 @comment unistd.h
2053 @comment Unix
2054 @deftypefun {char *} mktemp (char *@var{template})
2055 The @code{mktemp} function generates a unique file name by modifying
2056 @var{template} as described above.  If successful, it returns
2057 @var{template} as modified.  If @code{mktemp} cannot find a unique file
2058 name, it makes @var{template} an empty string and returns that.  If
2059 @var{template} does not end with @samp{XXXXXX}, @code{mktemp} returns a
2060 null pointer.
2061 @end deftypefun
2063 @comment unistd.h
2064 @comment BSD
2065 @deftypefun int mkstemp (char *@var{template})
2066 The @code{mkstemp} function generates a unique file name just as
2067 @code{mktemp} does, but it also opens the file for you with @code{open}
2068 (@pxref{Opening and Closing Files}).  If successful, it modifies
2069 @var{template} in place and returns a file descriptor open on that file
2070 for reading and writing.  If @code{mkstemp} cannot create a
2071 uniquely-named file, it makes @var{template} an empty string and returns
2072 @code{-1}.  If @var{template} does not end with @samp{XXXXXX},
2073 @code{mkstemp} returns @code{-1} and does not modify @var{template}.
2074 @end deftypefun
2076 Unlike @code{mktemp}, @code{mkstemp} is actually guaranteed to create a
2077 unique file that cannot possibly clash with any other program trying to
2078 create a temporary file.  This is because it works by calling
2079 @code{open} with the @code{O_EXCL} flag bit, which says you want to
2080 always create a new file, and get an error if the file already exists.