Set arch_minimum_kernel to 3.4.0 for x32
[glibc.git] / manual / filesys.texi
blob1cac45393d554a7a6a83c184262e2ce0be7c8885
1 @node File System Interface, Pipes and FIFOs, Low-Level I/O, Top
2 @c %MENU% Functions for manipulating files
3 @chapter File System Interface
5 This chapter describes @theglibc{}'s functions for manipulating
6 files.  Unlike the input and output functions (@pxref{I/O on Streams};
7 @pxref{Low-Level I/O}), these functions are concerned with operating
8 on the files themselves rather 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 * Working with Directory Trees:: Apply actions to all files or a selectable
21                                  subset of a directory hierarchy.
22 * Hard Links::                  Adding alternate names to a file.
23 * Symbolic Links::              A file that ``points to'' a file name.
24 * Deleting Files::              How to delete a file, and what that means.
25 * Renaming Files::              Changing a file's name.
26 * Creating Directories::        A system call just for creating a directory.
27 * File Attributes::             Attributes of individual files.
28 * Making Special Files::        How to create special files.
29 * Temporary Files::             Naming and creating temporary files.
30 @end menu
32 @node Working Directory
33 @section Working Directory
35 @cindex current working directory
36 @cindex working directory
37 @cindex change working directory
38 Each process has associated with it a directory, called its @dfn{current
39 working directory} or simply @dfn{working directory}, that is used in
40 the resolution of relative file names (@pxref{File Name Resolution}).
42 When you log in and begin a new session, your working directory is
43 initially set to the home directory associated with your login account
44 in the system user database.  You can find any user's home directory
45 using the @code{getpwuid} or @code{getpwnam} functions; see @ref{User
46 Database}.
48 Users can change the working directory using shell commands like
49 @code{cd}.  The functions described in this section are the primitives
50 used by those commands and by other programs for examining and changing
51 the working directory.
52 @pindex cd
54 Prototypes for these functions are declared in the header file
55 @file{unistd.h}.
56 @pindex unistd.h
58 @comment unistd.h
59 @comment POSIX.1
60 @deftypefun {char *} getcwd (char *@var{buffer}, size_t @var{size})
61 The @code{getcwd} function returns an absolute file name representing
62 the current working directory, storing it in the character array
63 @var{buffer} that you provide.  The @var{size} argument is how you tell
64 the system the allocation size of @var{buffer}.
66 The @glibcadj{} version of this function also permits you to specify a
67 null pointer for the @var{buffer} argument.  Then @code{getcwd}
68 allocates a buffer automatically, as with @code{malloc}
69 (@pxref{Unconstrained Allocation}).  If the @var{size} is greater than
70 zero, then the buffer is that large; otherwise, the buffer is as large
71 as necessary to hold the result.
73 The return value is @var{buffer} on success and a null pointer on failure.
74 The following @code{errno} error conditions are defined for this function:
76 @table @code
77 @item EINVAL
78 The @var{size} argument is zero and @var{buffer} is not a null pointer.
80 @item ERANGE
81 The @var{size} argument is less than the length of the working directory
82 name.  You need to allocate a bigger array and try again.
84 @item EACCES
85 Permission to read or search a component of the file name was denied.
86 @end table
87 @end deftypefun
89 You could implement the behavior of GNU's @w{@code{getcwd (NULL, 0)}}
90 using only the standard behavior of @code{getcwd}:
92 @smallexample
93 char *
94 gnu_getcwd ()
96   size_t size = 100;
98   while (1)
99     @{
100       char *buffer = (char *) xmalloc (size);
101       if (getcwd (buffer, size) == buffer)
102         return buffer;
103       free (buffer);
104       if (errno != ERANGE)
105         return 0;
106       size *= 2;
107     @}
109 @end smallexample
111 @noindent
112 @xref{Malloc Examples}, for information about @code{xmalloc}, which is
113 not a library function but is a customary name used in most GNU
114 software.
116 @comment unistd.h
117 @comment BSD
118 @deftypefn {Deprecated Function} {char *} getwd (char *@var{buffer})
119 This is similar to @code{getcwd}, but has no way to specify the size of
120 the buffer.  @Theglibc{} provides @code{getwd} only
121 for backwards compatibility with BSD.
123 The @var{buffer} argument should be a pointer to an array at least
124 @code{PATH_MAX} bytes long (@pxref{Limits for Files}).  On @gnuhurdsystems{}
125 there is no limit to the size of a file name, so this is not
126 necessarily enough space to contain the directory name.  That is why
127 this function is deprecated.
128 @end deftypefn
130 @comment unistd.h
131 @comment GNU
132 @deftypefun {char *} get_current_dir_name (void)
133 @vindex PWD
134 This @code{get_current_dir_name} function is basically equivalent to
135 @w{@code{getcwd (NULL, 0)}}.  The only difference is that the value of
136 the @code{PWD} variable is returned if this value is correct.  This is a
137 subtle difference which is visible if the path described by the
138 @code{PWD} value is using one or more symbol links in which case the
139 value returned by @code{getcwd} can resolve the symbol links and
140 therefore yield a different result.
142 This function is a GNU extension.
143 @end deftypefun
145 @comment unistd.h
146 @comment POSIX.1
147 @deftypefun int chdir (const char *@var{filename})
148 This function is used to set the process's working directory to
149 @var{filename}.
151 The normal, successful return value from @code{chdir} is @code{0}.  A
152 value of @code{-1} is returned to indicate an error.  The @code{errno}
153 error conditions defined for this function are the usual file name
154 syntax errors (@pxref{File Name Errors}), plus @code{ENOTDIR} if the
155 file @var{filename} is not a directory.
156 @end deftypefun
158 @comment unistd.h
159 @comment XPG
160 @deftypefun int fchdir (int @var{filedes})
161 This function is used to set the process's working directory to
162 directory associated with the file descriptor @var{filedes}.
164 The normal, successful return value from @code{fchdir} is @code{0}.  A
165 value of @code{-1} is returned to indicate an error.  The following
166 @code{errno} error conditions are defined for this function:
168 @table @code
169 @item EACCES
170 Read permission is denied for the directory named by @code{dirname}.
172 @item EBADF
173 The @var{filedes} argument is not a valid file descriptor.
175 @item ENOTDIR
176 The file descriptor @var{filedes} is not associated with a directory.
178 @item EINTR
179 The function call was interrupt by a signal.
181 @item EIO
182 An I/O error occurred.
183 @end table
184 @end deftypefun
187 @node Accessing Directories
188 @section Accessing Directories
189 @cindex accessing directories
190 @cindex reading from a directory
191 @cindex directories, accessing
193 The facilities described in this section let you read the contents of a
194 directory file.  This is useful if you want your program to list all the
195 files in a directory, perhaps as part of a menu.
197 @cindex directory stream
198 The @code{opendir} function opens a @dfn{directory stream} whose
199 elements are directory entries.  Alternatively @code{fdopendir} can be
200 used which can have advantages if the program needs to have more
201 control over the way the directory is opened for reading.  This
202 allows, for instance, to pass the @code{O_NOATIME} flag to
203 @code{open}.
205 You use the @code{readdir} function on the directory stream to
206 retrieve these entries, represented as @w{@code{struct dirent}}
207 objects.  The name of the file for each entry is stored in the
208 @code{d_name} member of this structure.  There are obvious parallels
209 here to the stream facilities for ordinary files, described in
210 @ref{I/O on Streams}.
212 @menu
213 * Directory Entries::           Format of one directory entry.
214 * Opening a Directory::         How to open a directory stream.
215 * Reading/Closing Directory::   How to read directory entries from the stream.
216 * Simple Directory Lister::     A very simple directory listing program.
217 * Random Access Directory::     Rereading part of the directory
218                                  already read with the same stream.
219 * Scanning Directory Content::  Get entries for user selected subset of
220                                  contents in given directory.
221 * Simple Directory Lister Mark II::  Revised version of the program.
222 @end menu
224 @node Directory Entries
225 @subsection Format of a Directory Entry
227 @pindex dirent.h
228 This section describes what you find in a single directory entry, as you
229 might obtain it from a directory stream.  All the symbols are declared
230 in the header file @file{dirent.h}.
232 @comment dirent.h
233 @comment POSIX.1
234 @deftp {Data Type} {struct dirent}
235 This is a structure type used to return information about directory
236 entries.  It contains the following fields:
238 @table @code
239 @item char d_name[]
240 This is the null-terminated file name component.  This is the only
241 field you can count on in all POSIX systems.
243 @item ino_t d_fileno
244 This is the file serial number.  For BSD compatibility, you can also
245 refer to this member as @code{d_ino}.  On @gnulinuxhurdsystems{} and most POSIX
246 systems, for most files this the same as the @code{st_ino} member that
247 @code{stat} will return for the file.  @xref{File Attributes}.
249 @item unsigned char d_namlen
250 This is the length of the file name, not including the terminating
251 null character.  Its type is @code{unsigned char} because that is the
252 integer type of the appropriate size.  This member is a BSD extension.
253 The symbol @code{_DIRENT_HAVE_D_NAMLEN} is defined if this member is
254 available.
256 @item unsigned char d_type
257 This is the type of the file, possibly unknown.  The following constants
258 are defined for its value:
260 @vtable @code
261 @item DT_UNKNOWN
262 The type is unknown.  Only some filesystems have full support to
263 return the type of the file, others might always return this value.
265 @item DT_REG
266 A regular file.
268 @item DT_DIR
269 A directory.
271 @item DT_FIFO
272 A named pipe, or FIFO.  @xref{FIFO Special Files}.
274 @item DT_SOCK
275 A local-domain socket.  @c !!! @xref{Local Domain}.
277 @item DT_CHR
278 A character device.
280 @item DT_BLK
281 A block device.
283 @item DT_LNK
284 A symbolic link.
285 @end vtable
287 This member is a BSD extension.  The symbol @code{_DIRENT_HAVE_D_TYPE}
288 is defined if this member is available.  On systems where it is used, it
289 corresponds to the file type bits in the @code{st_mode} member of
290 @code{struct stat}.  If the value cannot be determine the member
291 value is DT_UNKNOWN.  These two macros convert between @code{d_type}
292 values and @code{st_mode} values:
294 @comment dirent.h
295 @comment BSD
296 @deftypefun int IFTODT (mode_t @var{mode})
297 This returns the @code{d_type} value corresponding to @var{mode}.
298 @end deftypefun
300 @comment dirent.h
301 @comment BSD
302 @deftypefun mode_t DTTOIF (int @var{dtype})
303 This returns the @code{st_mode} value corresponding to @var{dtype}.
304 @end deftypefun
305 @end table
307 This structure may contain additional members in the future.  Their
308 availability is always announced in the compilation environment by a
309 macro names @code{_DIRENT_HAVE_D_@var{xxx}} where @var{xxx} is replaced
310 by the name of the new member.  For instance, the member @code{d_reclen}
311 available on some systems is announced through the macro
312 @code{_DIRENT_HAVE_D_RECLEN}.
314 When a file has multiple names, each name has its own directory entry.
315 The only way you can tell that the directory entries belong to a
316 single file is that they have the same value for the @code{d_fileno}
317 field.
319 File attributes such as size, modification times etc., are part of the
320 file itself, not of any particular directory entry.  @xref{File
321 Attributes}.
322 @end deftp
324 @node Opening a Directory
325 @subsection Opening a Directory Stream
327 @pindex dirent.h
328 This section describes how to open a directory stream.  All the symbols
329 are declared in the header file @file{dirent.h}.
331 @comment dirent.h
332 @comment POSIX.1
333 @deftp {Data Type} DIR
334 The @code{DIR} data type represents a directory stream.
335 @end deftp
337 You shouldn't ever allocate objects of the @code{struct dirent} or
338 @code{DIR} data types, since the directory access functions do that for
339 you.  Instead, you refer to these objects using the pointers returned by
340 the following functions.
342 @comment dirent.h
343 @comment POSIX.1
344 @deftypefun {DIR *} opendir (const char *@var{dirname})
345 The @code{opendir} function opens and returns a directory stream for
346 reading the directory whose file name is @var{dirname}.  The stream has
347 type @code{DIR *}.
349 If unsuccessful, @code{opendir} returns a null pointer.  In addition to
350 the usual file name errors (@pxref{File Name Errors}), the
351 following @code{errno} error conditions are defined for this function:
353 @table @code
354 @item EACCES
355 Read permission is denied for the directory named by @code{dirname}.
357 @item EMFILE
358 The process has too many files open.
360 @item ENFILE
361 The entire system, or perhaps the file system which contains the
362 directory, cannot support any additional open files at the moment.
363 (This problem cannot happen on @gnuhurdsystems{}.)
365 @item ENOMEM
366 Not enough memory available.
367 @end table
369 The @code{DIR} type is typically implemented using a file descriptor,
370 and the @code{opendir} function in terms of the @code{open} function.
371 @xref{Low-Level I/O}.  Directory streams and the underlying
372 file descriptors are closed on @code{exec} (@pxref{Executing a File}).
373 @end deftypefun
375 The directory which is opened for reading by @code{opendir} is
376 identified by the name.  In some situations this is not sufficient.
377 Or the way @code{opendir} implicitly creates a file descriptor for the
378 directory is not the way a program might want it.  In these cases an
379 alternative interface can be used.
381 @comment dirent.h
382 @comment GNU
383 @deftypefun {DIR *} fdopendir (int @var{fd})
384 The @code{fdopendir} function works just like @code{opendir} but
385 instead of taking a file name and opening a file descriptor for the
386 directory the caller is required to provide a file descriptor.  This
387 file descriptor is then used in subsequent uses of the returned
388 directory stream object.
390 The caller must make sure the file descriptor is associated with a
391 directory and it allows reading.
393 If the @code{fdopendir} call returns successfully the file descriptor
394 is now under the control of the system.  It can be used in the same
395 way the descriptor implicitly created by @code{opendir} can be used
396 but the program must not close the descriptor.
398 In case the function is unsuccessful it returns a null pointer and the
399 file descriptor remains to be usable by the program.  The following
400 @code{errno} error conditions are defined for this function:
402 @table @code
403 @item EBADF
404 The file descriptor is not valid.
406 @item ENOTDIR
407 The file descriptor is not associated with a directory.
409 @item EINVAL
410 The descriptor does not allow reading the directory content.
412 @item ENOMEM
413 Not enough memory available.
414 @end table
415 @end deftypefun
417 In some situations it can be desirable to get hold of the file
418 descriptor which is created by the @code{opendir} call.  For instance,
419 to switch the current working directory to the directory just read the
420 @code{fchdir} function could be used.  Historically the @code{DIR} type
421 was exposed and programs could access the fields.  This does not happen
422 in @theglibc{}.  Instead a separate function is provided to allow
423 access.
425 @comment dirent.h
426 @comment GNU
427 @deftypefun int dirfd (DIR *@var{dirstream})
428 The function @code{dirfd} returns the file descriptor associated with
429 the directory stream @var{dirstream}.  This descriptor can be used until
430 the directory is closed with @code{closedir}.  If the directory stream
431 implementation is not using file descriptors the return value is
432 @code{-1}.
433 @end deftypefun
435 @node Reading/Closing Directory
436 @subsection Reading and Closing a Directory Stream
438 @pindex dirent.h
439 This section describes how to read directory entries from a directory
440 stream, and how to close the stream when you are done with it.  All the
441 symbols are declared in the header file @file{dirent.h}.
443 @comment dirent.h
444 @comment POSIX.1
445 @deftypefun {struct dirent *} readdir (DIR *@var{dirstream})
446 This function reads the next entry from the directory.  It normally
447 returns a pointer to a structure containing information about the
448 file.  This structure is associated with the @var{dirstream} handle
449 and can be rewritten by a subsequent call.
451 @strong{Portability Note:} On some systems @code{readdir} may not
452 return entries for @file{.} and @file{..}, even though these are always
453 valid file names in any directory.  @xref{File Name Resolution}.
455 If there are no more entries in the directory or an error is detected,
456 @code{readdir} returns a null pointer.  The following @code{errno} error
457 conditions are defined for this function:
459 @table @code
460 @item EBADF
461 The @var{dirstream} argument is not valid.
462 @end table
464 To distinguish between an end-of-directory condition or an error, you
465 must set @code{errno} to zero before calling @code{readdir}.  To avoid
466 entering an infinite loop, you should stop reading from the directory
467 after the first error.
469 In POSIX.1-2008, @code{readdir} is not thread-safe.  In @theglibc{}
470 implementation, it is safe to call @code{readdir} concurrently on
471 different @var{dirstream}s, but multiple threads accessing the same
472 @var{dirstream} result in undefined behavior.  @code{readdir_r} is a
473 fully thread-safe alternative, but suffers from poor portability (see
474 below).  It is recommended that you use @code{readdir}, with external
475 locking if multiple threads access the same @var{dirstream}.
476 @end deftypefun
478 @comment dirent.h
479 @comment GNU
480 @deftypefun int readdir_r (DIR *@var{dirstream}, struct dirent *@var{entry}, struct dirent **@var{result})
481 This function is a version of @code{readdir} which performs internal
482 locking.  Like @code{readdir} it returns the next entry from the
483 directory.  To prevent conflicts between simultaneously running
484 threads the result is stored inside the @var{entry} object.
486 @strong{Portability Note:} It is recommended to use @code{readdir}
487 instead of @code{readdir_r} for the following reasons:
489 @itemize @bullet
490 @item
491 On systems which do not define @code{NAME_MAX}, it may not be possible
492 to use @code{readdir_r} safely because the caller does not specify the
493 length of the buffer for the directory entry.
495 @item
496 On some systems, @code{readdir_r} cannot read directory entries with
497 very long names.  If such a name is encountered, @theglibc{}
498 implementation of @code{readdir_r} returns with an error code of
499 @code{ENAMETOOLONG} after the final directory entry has been read.  On
500 other systems, @code{readdir_r} may return successfully, but the
501 @code{d_name} member may not be NUL-terminated or may be truncated.
503 @item
504 POSIX-1.2008 does not guarantee that @code{readdir} is thread-safe,
505 even when access to the same @var{dirstream} is serialized.  But in
506 current implementations (including @theglibc{}), it is safe to call
507 @code{readdir} concurrently on different @var{dirstream}s, so there is
508 no need to use @code{readdir_r} in most multi-threaded programs.  In
509 the rare case that multiple threads need to read from the same
510 @var{dirstream}, it is still better to use @code{readdir} and external
511 synchronization.
513 @item
514 It is expected that future versions of POSIX will obsolete
515 @code{readdir_r} and mandate the level of thread safety for
516 @code{readdir} which is provided by @theglibc{} and other
517 implementations today.
518 @end itemize
520 Normally @code{readdir_r} returns zero and sets @code{*@var{result}}
521 to @var{entry}.  If there are no more entries in the directory or an
522 error is detected, @code{readdir_r} sets @code{*@var{result}} to a
523 null pointer and returns a nonzero error code, also stored in
524 @code{errno}, as described for @code{readdir}.
526 It is also important to look at the definition of the @code{struct
527 dirent} type.  Simply passing a pointer to an object of this type for
528 the second parameter of @code{readdir_r} might not be enough.  Some
529 systems don't define the @code{d_name} element sufficiently long.  In
530 this case the user has to provide additional space.  There must be room
531 for at least @code{NAME_MAX + 1} characters in the @code{d_name} array.
532 Code to call @code{readdir_r} could look like this:
534 @smallexample
535   union
536   @{
537     struct dirent d;
538     char b[offsetof (struct dirent, d_name) + NAME_MAX + 1];
539   @} u;
541   if (readdir_r (dir, &u.d, &res) == 0)
542     @dots{}
543 @end smallexample
544 @end deftypefun
546 To support large filesystems on 32-bit machines there are LFS variants
547 of the last two functions.
549 @comment dirent.h
550 @comment LFS
551 @deftypefun {struct dirent64 *} readdir64 (DIR *@var{dirstream})
552 The @code{readdir64} function is just like the @code{readdir} function
553 except that it returns a pointer to a record of type @code{struct
554 dirent64}.  Some of the members of this data type (notably @code{d_ino})
555 might have a different size to allow large filesystems.
557 In all other aspects this function is equivalent to @code{readdir}.
558 @end deftypefun
560 @comment dirent.h
561 @comment LFS
562 @deftypefun int readdir64_r (DIR *@var{dirstream}, struct dirent64 *@var{entry}, struct dirent64 **@var{result})
563 The @code{readdir64_r} function is equivalent to the @code{readdir_r}
564 function except that it takes parameters of base type @code{struct
565 dirent64} instead of @code{struct dirent} in the second and third
566 position.  The same precautions mentioned in the documentation of
567 @code{readdir_r} also apply here.
568 @end deftypefun
570 @comment dirent.h
571 @comment POSIX.1
572 @deftypefun int closedir (DIR *@var{dirstream})
573 This function closes the directory stream @var{dirstream}.  It returns
574 @code{0} on success and @code{-1} on failure.
576 The following @code{errno} error conditions are defined for this
577 function:
579 @table @code
580 @item EBADF
581 The @var{dirstream} argument is not valid.
582 @end table
583 @end deftypefun
585 @node Simple Directory Lister
586 @subsection Simple Program to List a Directory
588 Here's a simple program that prints the names of the files in
589 the current working directory:
591 @smallexample
592 @include dir.c.texi
593 @end smallexample
595 The order in which files appear in a directory tends to be fairly
596 random.  A more useful program would sort the entries (perhaps by
597 alphabetizing them) before printing them; see
598 @ref{Scanning Directory Content}, and @ref{Array Sort Function}.
601 @node Random Access Directory
602 @subsection Random Access in a Directory Stream
604 @pindex dirent.h
605 This section describes how to reread parts of a directory that you have
606 already read from an open directory stream.  All the symbols are
607 declared in the header file @file{dirent.h}.
609 @comment dirent.h
610 @comment POSIX.1
611 @deftypefun void rewinddir (DIR *@var{dirstream})
612 The @code{rewinddir} function is used to reinitialize the directory
613 stream @var{dirstream}, so that if you call @code{readdir} it
614 returns information about the first entry in the directory again.  This
615 function also notices if files have been added or removed to the
616 directory since it was opened with @code{opendir}.  (Entries for these
617 files might or might not be returned by @code{readdir} if they were
618 added or removed since you last called @code{opendir} or
619 @code{rewinddir}.)
620 @end deftypefun
622 @comment dirent.h
623 @comment BSD
624 @deftypefun {long int} telldir (DIR *@var{dirstream})
625 The @code{telldir} function returns the file position of the directory
626 stream @var{dirstream}.  You can use this value with @code{seekdir} to
627 restore the directory stream to that position.
628 @end deftypefun
630 @comment dirent.h
631 @comment BSD
632 @deftypefun void seekdir (DIR *@var{dirstream}, long int @var{pos})
633 The @code{seekdir} function sets the file position of the directory
634 stream @var{dirstream} to @var{pos}.  The value @var{pos} must be the
635 result of a previous call to @code{telldir} on this particular stream;
636 closing and reopening the directory can invalidate values returned by
637 @code{telldir}.
638 @end deftypefun
641 @node Scanning Directory Content
642 @subsection Scanning the Content of a Directory
644 A higher-level interface to the directory handling functions is the
645 @code{scandir} function.  With its help one can select a subset of the
646 entries in a directory, possibly sort them and get a list of names as
647 the result.
649 @comment dirent.h
650 @comment BSD/SVID
651 @deftypefun int scandir (const char *@var{dir}, struct dirent ***@var{namelist}, int (*@var{selector}) (const struct dirent *), int (*@var{cmp}) (const struct dirent **, const struct dirent **))
653 The @code{scandir} function scans the contents of the directory selected
654 by @var{dir}.  The result in *@var{namelist} is an array of pointers to
655 structure of type @code{struct dirent} which describe all selected
656 directory entries and which is allocated using @code{malloc}.  Instead
657 of always getting all directory entries returned, the user supplied
658 function @var{selector} can be used to decide which entries are in the
659 result.  Only the entries for which @var{selector} returns a non-zero
660 value are selected.
662 Finally the entries in *@var{namelist} are sorted using the
663 user-supplied function @var{cmp}.  The arguments passed to the @var{cmp}
664 function are of type @code{struct dirent **}, therefore one cannot
665 directly use the @code{strcmp} or @code{strcoll} functions; instead see
666 the functions @code{alphasort} and @code{versionsort} below.
668 The return value of the function is the number of entries placed in
669 *@var{namelist}.  If it is @code{-1} an error occurred (either the
670 directory could not be opened for reading or the malloc call failed) and
671 the global variable @code{errno} contains more information on the error.
672 @end deftypefun
674 As described above the fourth argument to the @code{scandir} function
675 must be a pointer to a sorting function.  For the convenience of the
676 programmer @theglibc{} contains implementations of functions which
677 are very helpful for this purpose.
679 @comment dirent.h
680 @comment BSD/SVID
681 @deftypefun int alphasort (const void *@var{a}, const void *@var{b})
682 The @code{alphasort} function behaves like the @code{strcoll} function
683 (@pxref{String/Array Comparison}).  The difference is that the arguments
684 are not string pointers but instead they are of type
685 @code{struct dirent **}.
687 The return value of @code{alphasort} is less than, equal to, or greater
688 than zero depending on the order of the two entries @var{a} and @var{b}.
689 @end deftypefun
691 @comment dirent.h
692 @comment GNU
693 @deftypefun int versionsort (const void *@var{a}, const void *@var{b})
694 The @code{versionsort} function is like @code{alphasort} except that it
695 uses the @code{strverscmp} function internally.
696 @end deftypefun
698 If the filesystem supports large files we cannot use the @code{scandir}
699 anymore since the @code{dirent} structure might not able to contain all
700 the information.  The LFS provides the new type @w{@code{struct
701 dirent64}}.  To use this we need a new function.
703 @comment dirent.h
704 @comment GNU
705 @deftypefun int scandir64 (const char *@var{dir}, struct dirent64 ***@var{namelist}, int (*@var{selector}) (const struct dirent64 *), int (*@var{cmp}) (const struct dirent64 **, const struct dirent64 **))
706 The @code{scandir64} function works like the @code{scandir} function
707 except that the directory entries it returns are described by elements
708 of type @w{@code{struct dirent64}}.  The function pointed to by
709 @var{selector} is again used to select the desired entries, except that
710 @var{selector} now must point to a function which takes a
711 @w{@code{struct dirent64 *}} parameter.
713 Similarly the @var{cmp} function should expect its two arguments to be
714 of type @code{struct dirent64 **}.
715 @end deftypefun
717 As @var{cmp} is now a function of a different type, the functions
718 @code{alphasort} and @code{versionsort} cannot be supplied for that
719 argument.  Instead we provide the two replacement functions below.
721 @comment dirent.h
722 @comment GNU
723 @deftypefun int alphasort64 (const void *@var{a}, const void *@var{b})
724 The @code{alphasort64} function behaves like the @code{strcoll} function
725 (@pxref{String/Array Comparison}).  The difference is that the arguments
726 are not string pointers but instead they are of type
727 @code{struct dirent64 **}.
729 Return value of @code{alphasort64} is less than, equal to, or greater
730 than zero depending on the order of the two entries @var{a} and @var{b}.
731 @end deftypefun
733 @comment dirent.h
734 @comment GNU
735 @deftypefun int versionsort64 (const void *@var{a}, const void *@var{b})
736 The @code{versionsort64} function is like @code{alphasort64}, excepted that it
737 uses the @code{strverscmp} function internally.
738 @end deftypefun
740 It is important not to mix the use of @code{scandir} and the 64-bit
741 comparison functions or vice versa.  There are systems on which this
742 works but on others it will fail miserably.
744 @node Simple Directory Lister Mark II
745 @subsection Simple Program to List a Directory, Mark II
747 Here is a revised version of the directory lister found above
748 (@pxref{Simple Directory Lister}).  Using the @code{scandir} function we
749 can avoid the functions which work directly with the directory contents.
750 After the call the returned entries are available for direct use.
752 @smallexample
753 @include dir2.c.texi
754 @end smallexample
756 Note the simple selector function in this example.  Since we want to see
757 all directory entries we always return @code{1}.
760 @node Working with Directory Trees
761 @section Working with Directory Trees
762 @cindex directory hierarchy
763 @cindex hierarchy, directory
764 @cindex tree, directory
766 The functions described so far for handling the files in a directory
767 have allowed you to either retrieve the information bit by bit, or to
768 process all the files as a group (see @code{scandir}).  Sometimes it is
769 useful to process whole hierarchies of directories and their contained
770 files.  The X/Open specification defines two functions to do this.  The
771 simpler form is derived from an early definition in @w{System V} systems
772 and therefore this function is available on SVID-derived systems.  The
773 prototypes and required definitions can be found in the @file{ftw.h}
774 header.
776 There are four functions in this family: @code{ftw}, @code{nftw} and
777 their 64-bit counterparts @code{ftw64} and @code{nftw64}.  These
778 functions take as one of their arguments a pointer to a callback
779 function of the appropriate type.
781 @comment ftw.h
782 @comment GNU
783 @deftp {Data Type} __ftw_func_t
785 @smallexample
786 int (*) (const char *, const struct stat *, int)
787 @end smallexample
789 The type of callback functions given to the @code{ftw} function.  The
790 first parameter points to the file name, the second parameter to an
791 object of type @code{struct stat} which is filled in for the file named
792 in the first parameter.
794 @noindent
795 The last parameter is a flag giving more information about the current
796 file.  It can have the following values:
798 @vtable @code
799 @item FTW_F
800 The item is either a normal file or a file which does not fit into one
801 of the following categories.  This could be special files, sockets etc.
802 @item FTW_D
803 The item is a directory.
804 @item FTW_NS
805 The @code{stat} call failed and so the information pointed to by the
806 second paramater is invalid.
807 @item FTW_DNR
808 The item is a directory which cannot be read.
809 @item FTW_SL
810 The item is a symbolic link.  Since symbolic links are normally followed
811 seeing this value in a @code{ftw} callback function means the referenced
812 file does not exist.  The situation for @code{nftw} is different.
814 This value is only available if the program is compiled with
815 @code{_BSD_SOURCE} or @code{_XOPEN_EXTENDED} defined before including
816 the first header.  The original SVID systems do not have symbolic links.
817 @end vtable
819 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
820 type is in fact @code{__ftw64_func_t} since this mode changes
821 @code{struct stat} to be @code{struct stat64}.
822 @end deftp
824 For the LFS interface and for use in the function @code{ftw64}, the
825 header @file{ftw.h} defines another function type.
827 @comment ftw.h
828 @comment GNU
829 @deftp {Data Type} __ftw64_func_t
831 @smallexample
832 int (*) (const char *, const struct stat64 *, int)
833 @end smallexample
835 This type is used just like @code{__ftw_func_t} for the callback
836 function, but this time is called from @code{ftw64}.  The second
837 parameter to the function is a pointer to a variable of type
838 @code{struct stat64} which is able to represent the larger values.
839 @end deftp
841 @comment ftw.h
842 @comment GNU
843 @deftp {Data Type} __nftw_func_t
845 @smallexample
846 int (*) (const char *, const struct stat *, int, struct FTW *)
847 @end smallexample
849 @vindex FTW_DP
850 @vindex FTW_SLN
851 The first three arguments are the same as for the @code{__ftw_func_t}
852 type.  However for the third argument some additional values are defined
853 to allow finer differentiation:
854 @table @code
855 @item FTW_DP
856 The current item is a directory and all subdirectories have already been
857 visited and reported.  This flag is returned instead of @code{FTW_D} if
858 the @code{FTW_DEPTH} flag is passed to @code{nftw} (see below).
859 @item FTW_SLN
860 The current item is a stale symbolic link.  The file it points to does
861 not exist.
862 @end table
864 The last parameter of the callback function is a pointer to a structure
865 with some extra information as described below.
867 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
868 type is in fact @code{__nftw64_func_t} since this mode changes
869 @code{struct stat} to be @code{struct stat64}.
870 @end deftp
872 For the LFS interface there is also a variant of this data type
873 available which has to be used with the @code{nftw64} function.
875 @comment ftw.h
876 @comment GNU
877 @deftp {Data Type} __nftw64_func_t
879 @smallexample
880 int (*) (const char *, const struct stat64 *, int, struct FTW *)
881 @end smallexample
883 This type is used just like @code{__nftw_func_t} for the callback
884 function, but this time is called from @code{nftw64}.  The second
885 parameter to the function is this time a pointer to a variable of type
886 @code{struct stat64} which is able to represent the larger values.
887 @end deftp
889 @comment ftw.h
890 @comment XPG4.2
891 @deftp {Data Type} {struct FTW}
892 The information contained in this structure helps in interpreting the
893 name parameter and gives some information about the current state of the
894 traversal of the directory hierarchy.
896 @table @code
897 @item int base
898 The value is the offset into the string passed in the first parameter to
899 the callback function of the beginning of the file name.  The rest of
900 the string is the path of the file.  This information is especially
901 important if the @code{FTW_CHDIR} flag was set in calling @code{nftw}
902 since then the current directory is the one the current item is found
904 @item int level
905 Whilst processing, the code tracks how many directories down it has gone
906 to find the current file.  This nesting level starts at @math{0} for
907 files in the initial directory (or is zero for the initial file if a
908 file was passed).
909 @end table
910 @end deftp
913 @comment ftw.h
914 @comment SVID
915 @deftypefun int ftw (const char *@var{filename}, __ftw_func_t @var{func}, int @var{descriptors})
916 The @code{ftw} function calls the callback function given in the
917 parameter @var{func} for every item which is found in the directory
918 specified by @var{filename} and all directories below.  The function
919 follows symbolic links if necessary but does not process an item twice.
920 If @var{filename} is not a directory then it itself is the only object
921 returned to the callback function.
923 The file name passed to the callback function is constructed by taking
924 the @var{filename} parameter and appending the names of all passed
925 directories and then the local file name.  So the callback function can
926 use this parameter to access the file.  @code{ftw} also calls
927 @code{stat} for the file and passes that information on to the callback
928 function.  If this @code{stat} call was not successful the failure is
929 indicated by setting the third argument of the callback function to
930 @code{FTW_NS}.  Otherwise it is set according to the description given
931 in the account of @code{__ftw_func_t} above.
933 The callback function is expected to return @math{0} to indicate that no
934 error occurred and that processing should continue.  If an error
935 occurred in the callback function or it wants @code{ftw} to return
936 immediately, the callback function can return a value other than
937 @math{0}.  This is the only correct way to stop the function.  The
938 program must not use @code{setjmp} or similar techniques to continue
939 from another place.  This would leave resources allocated by the
940 @code{ftw} function unfreed.
942 The @var{descriptors} parameter to @code{ftw} specifies how many file
943 descriptors it is allowed to consume.  The function runs faster the more
944 descriptors it can use.  For each level in the directory hierarchy at
945 most one descriptor is used, but for very deep ones any limit on open
946 file descriptors for the process or the system may be exceeded.
947 Moreover, file descriptor limits in a multi-threaded program apply to
948 all the threads as a group, and therefore it is a good idea to supply a
949 reasonable limit to the number of open descriptors.
951 The return value of the @code{ftw} function is @math{0} if all callback
952 function calls returned @math{0} and all actions performed by the
953 @code{ftw} succeeded.  If a function call failed (other than calling
954 @code{stat} on an item) the function returns @math{-1}.  If a callback
955 function returns a value other than @math{0} this value is returned as
956 the return value of @code{ftw}.
958 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
959 32-bit system this function is in fact @code{ftw64}, i.e., the LFS
960 interface transparently replaces the old interface.
961 @end deftypefun
963 @comment ftw.h
964 @comment Unix98
965 @deftypefun int ftw64 (const char *@var{filename}, __ftw64_func_t @var{func}, int @var{descriptors})
966 This function is similar to @code{ftw} but it can work on filesystems
967 with large files.  File information is reported using a variable of type
968 @code{struct stat64} which is passed by reference to the callback
969 function.
971 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
972 32-bit system this function is available under the name @code{ftw} and
973 transparently replaces the old implementation.
974 @end deftypefun
976 @comment ftw.h
977 @comment XPG4.2
978 @deftypefun int nftw (const char *@var{filename}, __nftw_func_t @var{func}, int @var{descriptors}, int @var{flag})
979 The @code{nftw} function works like the @code{ftw} functions.  They call
980 the callback function @var{func} for all items found in the directory
981 @var{filename} and below.  At most @var{descriptors} file descriptors
982 are consumed during the @code{nftw} call.
984 One difference is that the callback function is of a different type.  It
985 is of type @w{@code{struct FTW *}} and provides the callback function
986 with the extra information described above.
988 A second difference is that @code{nftw} takes a fourth argument, which
989 is @math{0} or a bitwise-OR combination of any of the following values.
991 @vtable @code
992 @item FTW_PHYS
993 While traversing the directory symbolic links are not followed.  Instead
994 symbolic links are reported using the @code{FTW_SL} value for the type
995 parameter to the callback function.  If the file referenced by a
996 symbolic link does not exist @code{FTW_SLN} is returned instead.
997 @item FTW_MOUNT
998 The callback function is only called for items which are on the same
999 mounted filesystem as the directory given by the @var{filename}
1000 parameter to @code{nftw}.
1001 @item FTW_CHDIR
1002 If this flag is given the current working directory is changed to the
1003 directory of the reported object before the callback function is called.
1004 When @code{ntfw} finally returns the current directory is restored to
1005 its original value.
1006 @item FTW_DEPTH
1007 If this option is specified then all subdirectories and files within
1008 them are processed before processing the top directory itself
1009 (depth-first processing).  This also means the type flag given to the
1010 callback function is @code{FTW_DP} and not @code{FTW_D}.
1011 @item FTW_ACTIONRETVAL
1012 If this option is specified then return values from callbacks
1013 are handled differently.  If the callback returns @code{FTW_CONTINUE},
1014 walking continues normally.  @code{FTW_STOP} means walking stops
1015 and @code{FTW_STOP} is returned to the caller.  If @code{FTW_SKIP_SUBTREE}
1016 is returned by the callback with @code{FTW_D} argument, the subtree
1017 is skipped and walking continues with next sibling of the directory.
1018 If @code{FTW_SKIP_SIBLINGS} is returned by the callback, all siblings
1019 of the current entry are skipped and walking continues in its parent.
1020 No other return values should be returned from the callbacks if
1021 this option is set.  This option is a GNU extension.
1022 @end vtable
1024 The return value is computed in the same way as for @code{ftw}.
1025 @code{nftw} returns @math{0} if no failures occurred and all callback
1026 functions returned @math{0}.  In case of internal errors, such as memory
1027 problems, the return value is @math{-1} and @var{errno} is set
1028 accordingly.  If the return value of a callback invocation was non-zero
1029 then that value is returned.
1031 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1032 32-bit system this function is in fact @code{nftw64}, i.e., the LFS
1033 interface transparently replaces the old interface.
1034 @end deftypefun
1036 @comment ftw.h
1037 @comment Unix98
1038 @deftypefun int nftw64 (const char *@var{filename}, __nftw64_func_t @var{func}, int @var{descriptors}, int @var{flag})
1039 This function is similar to @code{nftw} but it can work on filesystems
1040 with large files.  File information is reported using a variable of type
1041 @code{struct stat64} which is passed by reference to the callback
1042 function.
1044 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1045 32-bit system this function is available under the name @code{nftw} and
1046 transparently replaces the old implementation.
1047 @end deftypefun
1050 @node Hard Links
1051 @section Hard Links
1052 @cindex hard link
1053 @cindex link, hard
1054 @cindex multiple names for one file
1055 @cindex file names, multiple
1057 In POSIX systems, one file can have many names at the same time.  All of
1058 the names are equally real, and no one of them is preferred to the
1059 others.
1061 To add a name to a file, use the @code{link} function.  (The new name is
1062 also called a @dfn{hard link} to the file.)  Creating a new link to a
1063 file does not copy the contents of the file; it simply makes a new name
1064 by which the file can be known, in addition to the file's existing name
1065 or names.
1067 One file can have names in several directories, so the organization
1068 of the file system is not a strict hierarchy or tree.
1070 In most implementations, it is not possible to have hard links to the
1071 same file in multiple file systems.  @code{link} reports an error if you
1072 try to make a hard link to the file from another file system when this
1073 cannot be done.
1075 The prototype for the @code{link} function is declared in the header
1076 file @file{unistd.h}.
1077 @pindex unistd.h
1079 @comment unistd.h
1080 @comment POSIX.1
1081 @deftypefun int link (const char *@var{oldname}, const char *@var{newname})
1082 The @code{link} function makes a new link to the existing file named by
1083 @var{oldname}, under the new name @var{newname}.
1085 This function returns a value of @code{0} if it is successful and
1086 @code{-1} on failure.  In addition to the usual file name errors
1087 (@pxref{File Name Errors}) for both @var{oldname} and @var{newname}, the
1088 following @code{errno} error conditions are defined for this function:
1090 @table @code
1091 @item EACCES
1092 You are not allowed to write to the directory in which the new link is
1093 to be written.
1094 @ignore
1095 Some implementations also require that the existing file be accessible
1096 by the caller, and use this error to report failure for that reason.
1097 @end ignore
1099 @item EEXIST
1100 There is already a file named @var{newname}.  If you want to replace
1101 this link with a new link, you must remove the old link explicitly first.
1103 @item EMLINK
1104 There are already too many links to the file named by @var{oldname}.
1105 (The maximum number of links to a file is @w{@code{LINK_MAX}}; see
1106 @ref{Limits for Files}.)
1108 @item ENOENT
1109 The file named by @var{oldname} doesn't exist.  You can't make a link to
1110 a file that doesn't exist.
1112 @item ENOSPC
1113 The directory or file system that would contain the new link is full
1114 and cannot be extended.
1116 @item EPERM
1117 On @gnulinuxhurdsystems{} and some others, you cannot make links to
1118 directories.
1119 Many systems allow only privileged users to do so.  This error
1120 is used to report the problem.
1122 @item EROFS
1123 The directory containing the new link can't be modified because it's on
1124 a read-only file system.
1126 @item EXDEV
1127 The directory specified in @var{newname} is on a different file system
1128 than the existing file.
1130 @item EIO
1131 A hardware error occurred while trying to read or write the to filesystem.
1132 @end table
1133 @end deftypefun
1135 @node Symbolic Links
1136 @section Symbolic Links
1137 @cindex soft link
1138 @cindex link, soft
1139 @cindex symbolic link
1140 @cindex link, symbolic
1142 @gnusystems{} support @dfn{soft links} or @dfn{symbolic links}.  This
1143 is a kind of ``file'' that is essentially a pointer to another file
1144 name.  Unlike hard links, symbolic links can be made to directories or
1145 across file systems with no restrictions.  You can also make a symbolic
1146 link to a name which is not the name of any file.  (Opening this link
1147 will fail until a file by that name is created.)  Likewise, if the
1148 symbolic link points to an existing file which is later deleted, the
1149 symbolic link continues to point to the same file name even though the
1150 name no longer names any file.
1152 The reason symbolic links work the way they do is that special things
1153 happen when you try to open the link.  The @code{open} function realizes
1154 you have specified the name of a link, reads the file name contained in
1155 the link, and opens that file name instead.  The @code{stat} function
1156 likewise operates on the file that the symbolic link points to, instead
1157 of on the link itself.
1159 By contrast, other operations such as deleting or renaming the file
1160 operate on the link itself.  The functions @code{readlink} and
1161 @code{lstat} also refrain from following symbolic links, because their
1162 purpose is to obtain information about the link.  @code{link}, the
1163 function that makes a hard link, does too.  It makes a hard link to the
1164 symbolic link, which one rarely wants.
1166 Some systems have for some functions operating on files have a limit on
1167 how many symbolic links are followed when resolving a path name.  The
1168 limit if it exists is published in the @file{sys/param.h} header file.
1170 @comment sys/param.h
1171 @comment BSD
1172 @deftypevr Macro int MAXSYMLINKS
1174 The macro @code{MAXSYMLINKS} specifies how many symlinks some function
1175 will follow before returning @code{ELOOP}.  Not all functions behave the
1176 same and this value is not the same a that returned for
1177 @code{_SC_SYMLOOP} by @code{sysconf}.  In fact, the @code{sysconf}
1178 result can indicate that there is no fixed limit although
1179 @code{MAXSYMLINKS} exists and has a finite value.
1180 @end deftypevr
1182 Prototypes for most of the functions listed in this section are in
1183 @file{unistd.h}.
1184 @pindex unistd.h
1186 @comment unistd.h
1187 @comment BSD
1188 @deftypefun int symlink (const char *@var{oldname}, const char *@var{newname})
1189 The @code{symlink} function makes a symbolic link to @var{oldname} named
1190 @var{newname}.
1192 The normal return value from @code{symlink} is @code{0}.  A return value
1193 of @code{-1} indicates an error.  In addition to the usual file name
1194 syntax errors (@pxref{File Name Errors}), the following @code{errno}
1195 error conditions are defined for this function:
1197 @table @code
1198 @item EEXIST
1199 There is already an existing file named @var{newname}.
1201 @item EROFS
1202 The file @var{newname} would exist on a read-only file system.
1204 @item ENOSPC
1205 The directory or file system cannot be extended to make the new link.
1207 @item EIO
1208 A hardware error occurred while reading or writing data on the disk.
1210 @ignore
1211 @comment not sure about these
1212 @item ELOOP
1213 There are too many levels of indirection.  This can be the result of
1214 circular symbolic links to directories.
1216 @item EDQUOT
1217 The new link can't be created because the user's disk quota has been
1218 exceeded.
1219 @end ignore
1220 @end table
1221 @end deftypefun
1223 @comment unistd.h
1224 @comment BSD
1225 @deftypefun ssize_t readlink (const char *@var{filename}, char *@var{buffer}, size_t @var{size})
1226 The @code{readlink} function gets the value of the symbolic link
1227 @var{filename}.  The file name that the link points to is copied into
1228 @var{buffer}.  This file name string is @emph{not} null-terminated;
1229 @code{readlink} normally returns the number of characters copied.  The
1230 @var{size} argument specifies the maximum number of characters to copy,
1231 usually the allocation size of @var{buffer}.
1233 If the return value equals @var{size}, you cannot tell whether or not
1234 there was room to return the entire name.  So make a bigger buffer and
1235 call @code{readlink} again.  Here is an example:
1237 @smallexample
1238 char *
1239 readlink_malloc (const char *filename)
1241   int size = 100;
1242   char *buffer = NULL;
1244   while (1)
1245     @{
1246       buffer = (char *) xrealloc (buffer, size);
1247       int nchars = readlink (filename, buffer, size);
1248       if (nchars < 0)
1249         @{
1250           free (buffer);
1251           return NULL;
1252         @}
1253       if (nchars < size)
1254         return buffer;
1255       size *= 2;
1256     @}
1258 @end smallexample
1260 @c @group  Invalid outside example.
1261 A value of @code{-1} is returned in case of error.  In addition to the
1262 usual file name errors (@pxref{File Name Errors}), the following
1263 @code{errno} error conditions are defined for this function:
1265 @table @code
1266 @item EINVAL
1267 The named file is not a symbolic link.
1269 @item EIO
1270 A hardware error occurred while reading or writing data on the disk.
1271 @end table
1272 @c @end group
1273 @end deftypefun
1275 In some situations it is desirable to resolve all the
1276 symbolic links to get the real
1277 name of a file where no prefix names a symbolic link which is followed
1278 and no filename in the path is @code{.} or @code{..}.  This is for
1279 instance desirable if files have to be compare in which case different
1280 names can refer to the same inode.
1282 @comment stdlib.h
1283 @comment GNU
1284 @deftypefun {char *} canonicalize_file_name (const char *@var{name})
1286 The @code{canonicalize_file_name} function returns the absolute name of
1287 the file named by @var{name} which contains no @code{.}, @code{..}
1288 components nor any repeated path separators (@code{/}) or symlinks.  The
1289 result is passed back as the return value of the function in a block of
1290 memory allocated with @code{malloc}.  If the result is not used anymore
1291 the memory should be freed with a call to @code{free}.
1293 If any of the path components is missing the function returns a NULL
1294 pointer.  This is also what is returned if the length of the path
1295 reaches or exceeds @code{PATH_MAX} characters.  In any case
1296 @code{errno} is set accordingly.
1298 @table @code
1299 @item ENAMETOOLONG
1300 The resulting path is too long.  This error only occurs on systems which
1301 have a limit on the file name length.
1303 @item EACCES
1304 At least one of the path components is not readable.
1306 @item ENOENT
1307 The input file name is empty.
1309 @item ENOENT
1310 At least one of the path components does not exist.
1312 @item ELOOP
1313 More than @code{MAXSYMLINKS} many symlinks have been followed.
1314 @end table
1316 This function is a GNU extension and is declared in @file{stdlib.h}.
1317 @end deftypefun
1319 The Unix standard includes a similar function which differs from
1320 @code{canonicalize_file_name} in that the user has to provide the buffer
1321 where the result is placed in.
1323 @comment stdlib.h
1324 @comment XPG
1325 @deftypefun {char *} realpath (const char *restrict @var{name}, char *restrict @var{resolved})
1327 A call to @code{realpath} where the @var{resolved} parameter is
1328 @code{NULL} behaves exactly like @code{canonicalize_file_name}.  The
1329 function allocates a buffer for the file name and returns a pointer to
1330 it.  If @var{resolved} is not @code{NULL} it points to a buffer into
1331 which the result is copied.  It is the callers responsibility to
1332 allocate a buffer which is large enough.  On systems which define
1333 @code{PATH_MAX} this means the buffer must be large enough for a
1334 pathname of this size.  For systems without limitations on the pathname
1335 length the requirement cannot be met and programs should not call
1336 @code{realpath} with anything but @code{NULL} for the second parameter.
1338 One other difference is that the buffer @var{resolved} (if nonzero) will
1339 contain the part of the path component which does not exist or is not
1340 readable if the function returns @code{NULL} and @code{errno} is set to
1341 @code{EACCES} or @code{ENOENT}.
1343 This function is declared in @file{stdlib.h}.
1344 @end deftypefun
1346 The advantage of using this function is that it is more widely
1347 available.  The drawback is that it reports failures for long path on
1348 systems which have no limits on the file name length.
1350 @node Deleting Files
1351 @section Deleting Files
1352 @cindex deleting a file
1353 @cindex removing a file
1354 @cindex unlinking a file
1356 You can delete a file with @code{unlink} or @code{remove}.
1358 Deletion actually deletes a file name.  If this is the file's only name,
1359 then the file is deleted as well.  If the file has other remaining names
1360 (@pxref{Hard Links}), it remains accessible under those names.
1362 @comment unistd.h
1363 @comment POSIX.1
1364 @deftypefun int unlink (const char *@var{filename})
1365 The @code{unlink} function deletes the file name @var{filename}.  If
1366 this is a file's sole name, the file itself is also deleted.  (Actually,
1367 if any process has the file open when this happens, deletion is
1368 postponed until all processes have closed the file.)
1370 @pindex unistd.h
1371 The function @code{unlink} is declared in the header file @file{unistd.h}.
1373 This function returns @code{0} on successful completion, and @code{-1}
1374 on error.  In addition to the usual file name errors
1375 (@pxref{File Name Errors}), the following @code{errno} error conditions are
1376 defined for this function:
1378 @table @code
1379 @item EACCES
1380 Write permission is denied for the directory from which the file is to be
1381 removed, or the directory has the sticky bit set and you do not own the file.
1383 @item EBUSY
1384 This error indicates that the file is being used by the system in such a
1385 way that it can't be unlinked.  For example, you might see this error if
1386 the file name specifies the root directory or a mount point for a file
1387 system.
1389 @item ENOENT
1390 The file name to be deleted doesn't exist.
1392 @item EPERM
1393 On some systems @code{unlink} cannot be used to delete the name of a
1394 directory, or at least can only be used this way by a privileged user.
1395 To avoid such problems, use @code{rmdir} to delete directories.  (On
1396 @gnulinuxhurdsystems{} @code{unlink} can never delete the name of a directory.)
1398 @item EROFS
1399 The directory containing the file name to be deleted is on a read-only
1400 file system and can't be modified.
1401 @end table
1402 @end deftypefun
1404 @comment unistd.h
1405 @comment POSIX.1
1406 @deftypefun int rmdir (const char *@var{filename})
1407 @cindex directories, deleting
1408 @cindex deleting a directory
1409 The @code{rmdir} function deletes a directory.  The directory must be
1410 empty before it can be removed; in other words, it can only contain
1411 entries for @file{.} and @file{..}.
1413 In most other respects, @code{rmdir} behaves like @code{unlink}.  There
1414 are two additional @code{errno} error conditions defined for
1415 @code{rmdir}:
1417 @table @code
1418 @item ENOTEMPTY
1419 @itemx EEXIST
1420 The directory to be deleted is not empty.
1421 @end table
1423 These two error codes are synonymous; some systems use one, and some use
1424 the other.  @gnulinuxhurdsystems{} always use @code{ENOTEMPTY}.
1426 The prototype for this function is declared in the header file
1427 @file{unistd.h}.
1428 @pindex unistd.h
1429 @end deftypefun
1431 @comment stdio.h
1432 @comment ISO
1433 @deftypefun int remove (const char *@var{filename})
1434 This is the @w{ISO C} function to remove a file.  It works like
1435 @code{unlink} for files and like @code{rmdir} for directories.
1436 @code{remove} is declared in @file{stdio.h}.
1437 @pindex stdio.h
1438 @end deftypefun
1440 @node Renaming Files
1441 @section Renaming Files
1443 The @code{rename} function is used to change a file's name.
1445 @cindex renaming a file
1446 @comment stdio.h
1447 @comment ISO
1448 @deftypefun int rename (const char *@var{oldname}, const char *@var{newname})
1449 The @code{rename} function renames the file @var{oldname} to
1450 @var{newname}.  The file formerly accessible under the name
1451 @var{oldname} is afterwards accessible as @var{newname} instead.  (If
1452 the file had any other names aside from @var{oldname}, it continues to
1453 have those names.)
1455 The directory containing the name @var{newname} must be on the same file
1456 system as the directory containing the name @var{oldname}.
1458 One special case for @code{rename} is when @var{oldname} and
1459 @var{newname} are two names for the same file.  The consistent way to
1460 handle this case is to delete @var{oldname}.  However, in this case
1461 POSIX requires that @code{rename} do nothing and report success---which
1462 is inconsistent.  We don't know what your operating system will do.
1464 If @var{oldname} is not a directory, then any existing file named
1465 @var{newname} is removed during the renaming operation.  However, if
1466 @var{newname} is the name of a directory, @code{rename} fails in this
1467 case.
1469 If @var{oldname} is a directory, then either @var{newname} must not
1470 exist or it must name a directory that is empty.  In the latter case,
1471 the existing directory named @var{newname} is deleted first.  The name
1472 @var{newname} must not specify a subdirectory of the directory
1473 @code{oldname} which is being renamed.
1475 One useful feature of @code{rename} is that the meaning of @var{newname}
1476 changes ``atomically'' from any previously existing file by that name to
1477 its new meaning (i.e., the file that was called @var{oldname}).  There is
1478 no instant at which @var{newname} is non-existent ``in between'' the old
1479 meaning and the new meaning.  If there is a system crash during the
1480 operation, it is possible for both names to still exist; but
1481 @var{newname} will always be intact if it exists at all.
1483 If @code{rename} fails, it returns @code{-1}.  In addition to the usual
1484 file name errors (@pxref{File Name Errors}), the following
1485 @code{errno} error conditions are defined for this function:
1487 @table @code
1488 @item EACCES
1489 One of the directories containing @var{newname} or @var{oldname}
1490 refuses write permission; or @var{newname} and @var{oldname} are
1491 directories and write permission is refused for one of them.
1493 @item EBUSY
1494 A directory named by @var{oldname} or @var{newname} is being used by
1495 the system in a way that prevents the renaming from working.  This includes
1496 directories that are mount points for filesystems, and directories
1497 that are the current working directories of processes.
1499 @item ENOTEMPTY
1500 @itemx EEXIST
1501 The directory @var{newname} isn't empty.  @gnulinuxhurdsystems{} always return
1502 @code{ENOTEMPTY} for this, but some other systems return @code{EEXIST}.
1504 @item EINVAL
1505 @var{oldname} is a directory that contains @var{newname}.
1507 @item EISDIR
1508 @var{newname} is a directory but the @var{oldname} isn't.
1510 @item EMLINK
1511 The parent directory of @var{newname} would have too many links
1512 (entries).
1514 @item ENOENT
1515 The file @var{oldname} doesn't exist.
1517 @item ENOSPC
1518 The directory that would contain @var{newname} has no room for another
1519 entry, and there is no space left in the file system to expand it.
1521 @item EROFS
1522 The operation would involve writing to a directory on a read-only file
1523 system.
1525 @item EXDEV
1526 The two file names @var{newname} and @var{oldname} are on different
1527 file systems.
1528 @end table
1529 @end deftypefun
1531 @node Creating Directories
1532 @section Creating Directories
1533 @cindex creating a directory
1534 @cindex directories, creating
1536 @pindex mkdir
1537 Directories are created with the @code{mkdir} function.  (There is also
1538 a shell command @code{mkdir} which does the same thing.)
1539 @c !!! umask
1541 @comment sys/stat.h
1542 @comment POSIX.1
1543 @deftypefun int mkdir (const char *@var{filename}, mode_t @var{mode})
1544 The @code{mkdir} function creates a new, empty directory with name
1545 @var{filename}.
1547 The argument @var{mode} specifies the file permissions for the new
1548 directory file.  @xref{Permission Bits}, for more information about
1549 this.
1551 A return value of @code{0} indicates successful completion, and
1552 @code{-1} indicates failure.  In addition to the usual file name syntax
1553 errors (@pxref{File Name Errors}), the following @code{errno} error
1554 conditions are defined for this function:
1556 @table @code
1557 @item EACCES
1558 Write permission is denied for the parent directory in which the new
1559 directory is to be added.
1561 @item EEXIST
1562 A file named @var{filename} already exists.
1564 @item EMLINK
1565 The parent directory has too many links (entries).
1567 Well-designed file systems never report this error, because they permit
1568 more links than your disk could possibly hold.  However, you must still
1569 take account of the possibility of this error, as it could result from
1570 network access to a file system on another machine.
1572 @item ENOSPC
1573 The file system doesn't have enough room to create the new directory.
1575 @item EROFS
1576 The parent directory of the directory being created is on a read-only
1577 file system and cannot be modified.
1578 @end table
1580 To use this function, your program should include the header file
1581 @file{sys/stat.h}.
1582 @pindex sys/stat.h
1583 @end deftypefun
1585 @node File Attributes
1586 @section File Attributes
1588 @pindex ls
1589 When you issue an @samp{ls -l} shell command on a file, it gives you
1590 information about the size of the file, who owns it, when it was last
1591 modified, etc.  These are called the @dfn{file attributes}, and are
1592 associated with the file itself and not a particular one of its names.
1594 This section contains information about how you can inquire about and
1595 modify the attributes of a file.
1597 @menu
1598 * Attribute Meanings::          The names of the file attributes,
1599                                  and what their values mean.
1600 * Reading Attributes::          How to read the attributes of a file.
1601 * Testing File Type::           Distinguishing ordinary files,
1602                                  directories, links@dots{}
1603 * File Owner::                  How ownership for new files is determined,
1604                                  and how to change it.
1605 * Permission Bits::             How information about a file's access
1606                                  mode is stored.
1607 * Access Permission::           How the system decides who can access a file.
1608 * Setting Permissions::         How permissions for new files are assigned,
1609                                  and how to change them.
1610 * Testing File Access::         How to find out if your process can
1611                                  access a file.
1612 * File Times::                  About the time attributes of a file.
1613 * File Size::                   Manually changing the size of a file.
1614 @end menu
1616 @node Attribute Meanings
1617 @subsection The meaning of the File Attributes
1618 @cindex status of a file
1619 @cindex attributes of a file
1620 @cindex file attributes
1622 When you read the attributes of a file, they come back in a structure
1623 called @code{struct stat}.  This section describes the names of the
1624 attributes, their data types, and what they mean.  For the functions
1625 to read the attributes of a file, see @ref{Reading Attributes}.
1627 The header file @file{sys/stat.h} declares all the symbols defined
1628 in this section.
1629 @pindex sys/stat.h
1631 @comment sys/stat.h
1632 @comment POSIX.1
1633 @deftp {Data Type} {struct stat}
1634 The @code{stat} structure type is used to return information about the
1635 attributes of a file.  It contains at least the following members:
1637 @table @code
1638 @item mode_t st_mode
1639 Specifies the mode of the file.  This includes file type information
1640 (@pxref{Testing File Type}) and the file permission bits
1641 (@pxref{Permission Bits}).
1643 @item ino_t st_ino
1644 The file serial number, which distinguishes this file from all other
1645 files on the same device.
1647 @item dev_t st_dev
1648 Identifies the device containing the file.  The @code{st_ino} and
1649 @code{st_dev}, taken together, uniquely identify the file.  The
1650 @code{st_dev} value is not necessarily consistent across reboots or
1651 system crashes, however.
1653 @item nlink_t st_nlink
1654 The number of hard links to the file.  This count keeps track of how
1655 many directories have entries for this file.  If the count is ever
1656 decremented to zero, then the file itself is discarded as soon as no
1657 process still holds it open.  Symbolic links are not counted in the
1658 total.
1660 @item uid_t st_uid
1661 The user ID of the file's owner.  @xref{File Owner}.
1663 @item gid_t st_gid
1664 The group ID of the file.  @xref{File Owner}.
1666 @item off_t st_size
1667 This specifies the size of a regular file in bytes.  For files that are
1668 really devices this field isn't usually meaningful.  For symbolic links
1669 this specifies the length of the file name the link refers to.
1671 @item time_t st_atime
1672 This is the last access time for the file.  @xref{File Times}.
1674 @item unsigned long int st_atime_usec
1675 This is the fractional part of the last access time for the file.
1676 @xref{File Times}.
1678 @item time_t st_mtime
1679 This is the time of the last modification to the contents of the file.
1680 @xref{File Times}.
1682 @item unsigned long int st_mtime_usec
1683 This is the fractional part of the time of the last modification to the
1684 contents of the file.  @xref{File Times}.
1686 @item time_t st_ctime
1687 This is the time of the last modification to the attributes of the file.
1688 @xref{File Times}.
1690 @item unsigned long int st_ctime_usec
1691 This is the fractional part of the time of the last modification to the
1692 attributes of the file.  @xref{File Times}.
1694 @c !!! st_rdev
1695 @item blkcnt_t st_blocks
1696 This is the amount of disk space that the file occupies, measured in
1697 units of 512-byte blocks.
1699 The number of disk blocks is not strictly proportional to the size of
1700 the file, for two reasons: the file system may use some blocks for
1701 internal record keeping; and the file may be sparse---it may have
1702 ``holes'' which contain zeros but do not actually take up space on the
1703 disk.
1705 You can tell (approximately) whether a file is sparse by comparing this
1706 value with @code{st_size}, like this:
1708 @smallexample
1709 (st.st_blocks * 512 < st.st_size)
1710 @end smallexample
1712 This test is not perfect because a file that is just slightly sparse
1713 might not be detected as sparse at all.  For practical applications,
1714 this is not a problem.
1716 @item unsigned int st_blksize
1717 The optimal block size for reading of writing this file, in bytes.  You
1718 might use this size for allocating the buffer space for reading of
1719 writing the file.  (This is unrelated to @code{st_blocks}.)
1720 @end table
1721 @end deftp
1723 The extensions for the Large File Support (LFS) require, even on 32-bit
1724 machines, types which can handle file sizes up to @math{2^63}.
1725 Therefore a new definition of @code{struct stat} is necessary.
1727 @comment sys/stat.h
1728 @comment LFS
1729 @deftp {Data Type} {struct stat64}
1730 The members of this type are the same and have the same names as those
1731 in @code{struct stat}.  The only difference is that the members
1732 @code{st_ino}, @code{st_size}, and @code{st_blocks} have a different
1733 type to support larger values.
1735 @table @code
1736 @item mode_t st_mode
1737 Specifies the mode of the file.  This includes file type information
1738 (@pxref{Testing File Type}) and the file permission bits
1739 (@pxref{Permission Bits}).
1741 @item ino64_t st_ino
1742 The file serial number, which distinguishes this file from all other
1743 files on the same device.
1745 @item dev_t st_dev
1746 Identifies the device containing the file.  The @code{st_ino} and
1747 @code{st_dev}, taken together, uniquely identify the file.  The
1748 @code{st_dev} value is not necessarily consistent across reboots or
1749 system crashes, however.
1751 @item nlink_t st_nlink
1752 The number of hard links to the file.  This count keeps track of how
1753 many directories have entries for this file.  If the count is ever
1754 decremented to zero, then the file itself is discarded as soon as no
1755 process still holds it open.  Symbolic links are not counted in the
1756 total.
1758 @item uid_t st_uid
1759 The user ID of the file's owner.  @xref{File Owner}.
1761 @item gid_t st_gid
1762 The group ID of the file.  @xref{File Owner}.
1764 @item off64_t st_size
1765 This specifies the size of a regular file in bytes.  For files that are
1766 really devices this field isn't usually meaningful.  For symbolic links
1767 this specifies the length of the file name the link refers to.
1769 @item time_t st_atime
1770 This is the last access time for the file.  @xref{File Times}.
1772 @item unsigned long int st_atime_usec
1773 This is the fractional part of the last access time for the file.
1774 @xref{File Times}.
1776 @item time_t st_mtime
1777 This is the time of the last modification to the contents of the file.
1778 @xref{File Times}.
1780 @item unsigned long int st_mtime_usec
1781 This is the fractional part of the time of the last modification to the
1782 contents of the file.  @xref{File Times}.
1784 @item time_t st_ctime
1785 This is the time of the last modification to the attributes of the file.
1786 @xref{File Times}.
1788 @item unsigned long int st_ctime_usec
1789 This is the fractional part of the time of the last modification to the
1790 attributes of the file.  @xref{File Times}.
1792 @c !!! st_rdev
1793 @item blkcnt64_t st_blocks
1794 This is the amount of disk space that the file occupies, measured in
1795 units of 512-byte blocks.
1797 @item unsigned int st_blksize
1798 The optimal block size for reading of writing this file, in bytes.  You
1799 might use this size for allocating the buffer space for reading of
1800 writing the file.  (This is unrelated to @code{st_blocks}.)
1801 @end table
1802 @end deftp
1804 Some of the file attributes have special data type names which exist
1805 specifically for those attributes.  (They are all aliases for well-known
1806 integer types that you know and love.)  These typedef names are defined
1807 in the header file @file{sys/types.h} as well as in @file{sys/stat.h}.
1808 Here is a list of them.
1810 @comment sys/types.h
1811 @comment POSIX.1
1812 @deftp {Data Type} mode_t
1813 This is an integer data type used to represent file modes.  In
1814 @theglibc{}, this is an unsigned type no narrower than @code{unsigned
1815 int}.
1816 @end deftp
1818 @cindex inode number
1819 @comment sys/types.h
1820 @comment POSIX.1
1821 @deftp {Data Type} ino_t
1822 This is an unsigned integer type used to represent file serial numbers.
1823 (In Unix jargon, these are sometimes called @dfn{inode numbers}.)
1824 In @theglibc{}, this type is no narrower than @code{unsigned int}.
1826 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1827 is transparently replaced by @code{ino64_t}.
1828 @end deftp
1830 @comment sys/types.h
1831 @comment Unix98
1832 @deftp {Data Type} ino64_t
1833 This is an unsigned integer type used to represent file serial numbers
1834 for the use in LFS.  In @theglibc{}, this type is no narrower than
1835 @code{unsigned int}.
1837 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1838 available under the name @code{ino_t}.
1839 @end deftp
1841 @comment sys/types.h
1842 @comment POSIX.1
1843 @deftp {Data Type} dev_t
1844 This is an arithmetic data type used to represent file device numbers.
1845 In @theglibc{}, this is an integer type no narrower than @code{int}.
1846 @end deftp
1848 @comment sys/types.h
1849 @comment POSIX.1
1850 @deftp {Data Type} nlink_t
1851 This is an integer type used to represent file link counts.
1852 @end deftp
1854 @comment sys/types.h
1855 @comment Unix98
1856 @deftp {Data Type} blkcnt_t
1857 This is a signed integer type used to represent block counts.
1858 In @theglibc{}, this type is no narrower than @code{int}.
1860 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1861 is transparently replaced by @code{blkcnt64_t}.
1862 @end deftp
1864 @comment sys/types.h
1865 @comment Unix98
1866 @deftp {Data Type} blkcnt64_t
1867 This is a signed integer type used to represent block counts for the
1868 use in LFS.  In @theglibc{}, this type is no narrower than @code{int}.
1870 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1871 available under the name @code{blkcnt_t}.
1872 @end deftp
1874 @node Reading Attributes
1875 @subsection Reading the Attributes of a File
1877 To examine the attributes of files, use the functions @code{stat},
1878 @code{fstat} and @code{lstat}.  They return the attribute information in
1879 a @code{struct stat} object.  All three functions are declared in the
1880 header file @file{sys/stat.h}.
1882 @comment sys/stat.h
1883 @comment POSIX.1
1884 @deftypefun int stat (const char *@var{filename}, struct stat *@var{buf})
1885 The @code{stat} function returns information about the attributes of the
1886 file named by @w{@var{filename}} in the structure pointed to by @var{buf}.
1888 If @var{filename} is the name of a symbolic link, the attributes you get
1889 describe the file that the link points to.  If the link points to a
1890 nonexistent file name, then @code{stat} fails reporting a nonexistent
1891 file.
1893 The return value is @code{0} if the operation is successful, or
1894 @code{-1} on failure.  In addition to the usual file name errors
1895 (@pxref{File Name Errors}, the following @code{errno} error conditions
1896 are defined for this function:
1898 @table @code
1899 @item ENOENT
1900 The file named by @var{filename} doesn't exist.
1901 @end table
1903 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1904 function is in fact @code{stat64} since the LFS interface transparently
1905 replaces the normal implementation.
1906 @end deftypefun
1908 @comment sys/stat.h
1909 @comment Unix98
1910 @deftypefun int stat64 (const char *@var{filename}, struct stat64 *@var{buf})
1911 This function is similar to @code{stat} but it is also able to work on
1912 files larger than @math{2^31} bytes on 32-bit systems.  To be able to do
1913 this the result is stored in a variable of type @code{struct stat64} to
1914 which @var{buf} must point.
1916 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1917 function is available under the name @code{stat} and so transparently
1918 replaces the interface for small files on 32-bit machines.
1919 @end deftypefun
1921 @comment sys/stat.h
1922 @comment POSIX.1
1923 @deftypefun int fstat (int @var{filedes}, struct stat *@var{buf})
1924 The @code{fstat} function is like @code{stat}, except that it takes an
1925 open file descriptor as an argument instead of a file name.
1926 @xref{Low-Level I/O}.
1928 Like @code{stat}, @code{fstat} returns @code{0} on success and @code{-1}
1929 on failure.  The following @code{errno} error conditions are defined for
1930 @code{fstat}:
1932 @table @code
1933 @item EBADF
1934 The @var{filedes} argument is not a valid file descriptor.
1935 @end table
1937 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1938 function is in fact @code{fstat64} since the LFS interface transparently
1939 replaces the normal implementation.
1940 @end deftypefun
1942 @comment sys/stat.h
1943 @comment Unix98
1944 @deftypefun int fstat64 (int @var{filedes}, struct stat64 *@var{buf})
1945 This function is similar to @code{fstat} but is able to work on large
1946 files on 32-bit platforms.  For large files the file descriptor
1947 @var{filedes} should be obtained by @code{open64} or @code{creat64}.
1948 The @var{buf} pointer points to a variable of type @code{struct stat64}
1949 which is able to represent the larger values.
1951 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1952 function is available under the name @code{fstat} and so transparently
1953 replaces the interface for small files on 32-bit machines.
1954 @end deftypefun
1956 @comment sys/stat.h
1957 @comment BSD
1958 @deftypefun int lstat (const char *@var{filename}, struct stat *@var{buf})
1959 The @code{lstat} function is like @code{stat}, except that it does not
1960 follow symbolic links.  If @var{filename} is the name of a symbolic
1961 link, @code{lstat} returns information about the link itself; otherwise
1962 @code{lstat} works like @code{stat}.  @xref{Symbolic Links}.
1964 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1965 function is in fact @code{lstat64} since the LFS interface transparently
1966 replaces the normal implementation.
1967 @end deftypefun
1969 @comment sys/stat.h
1970 @comment Unix98
1971 @deftypefun int lstat64 (const char *@var{filename}, struct stat64 *@var{buf})
1972 This function is similar to @code{lstat} but it is also able to work on
1973 files larger than @math{2^31} bytes on 32-bit systems.  To be able to do
1974 this the result is stored in a variable of type @code{struct stat64} to
1975 which @var{buf} must point.
1977 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1978 function is available under the name @code{lstat} and so transparently
1979 replaces the interface for small files on 32-bit machines.
1980 @end deftypefun
1982 @node Testing File Type
1983 @subsection Testing the Type of a File
1985 The @dfn{file mode}, stored in the @code{st_mode} field of the file
1986 attributes, contains two kinds of information: the file type code, and
1987 the access permission bits.  This section discusses only the type code,
1988 which you can use to tell whether the file is a directory, socket,
1989 symbolic link, and so on.  For details about access permissions see
1990 @ref{Permission Bits}.
1992 There are two ways you can access the file type information in a file
1993 mode.  Firstly, for each file type there is a @dfn{predicate macro}
1994 which examines a given file mode and returns whether it is of that type
1995 or not.  Secondly, you can mask out the rest of the file mode to leave
1996 just the file type code, and compare this against constants for each of
1997 the supported file types.
1999 All of the symbols listed in this section are defined in the header file
2000 @file{sys/stat.h}.
2001 @pindex sys/stat.h
2003 The following predicate macros test the type of a file, given the value
2004 @var{m} which is the @code{st_mode} field returned by @code{stat} on
2005 that file:
2007 @comment sys/stat.h
2008 @comment POSIX
2009 @deftypefn Macro int S_ISDIR (mode_t @var{m})
2010 This macro returns non-zero if the file is a directory.
2011 @end deftypefn
2013 @comment sys/stat.h
2014 @comment POSIX
2015 @deftypefn Macro int S_ISCHR (mode_t @var{m})
2016 This macro returns non-zero if the file is a character special file (a
2017 device like a terminal).
2018 @end deftypefn
2020 @comment sys/stat.h
2021 @comment POSIX
2022 @deftypefn Macro int S_ISBLK (mode_t @var{m})
2023 This macro returns non-zero if the file is a block special file (a device
2024 like a disk).
2025 @end deftypefn
2027 @comment sys/stat.h
2028 @comment POSIX
2029 @deftypefn Macro int S_ISREG (mode_t @var{m})
2030 This macro returns non-zero if the file is a regular file.
2031 @end deftypefn
2033 @comment sys/stat.h
2034 @comment POSIX
2035 @deftypefn Macro int S_ISFIFO (mode_t @var{m})
2036 This macro returns non-zero if the file is a FIFO special file, or a
2037 pipe.  @xref{Pipes and FIFOs}.
2038 @end deftypefn
2040 @comment sys/stat.h
2041 @comment GNU
2042 @deftypefn Macro int S_ISLNK (mode_t @var{m})
2043 This macro returns non-zero if the file is a symbolic link.
2044 @xref{Symbolic Links}.
2045 @end deftypefn
2047 @comment sys/stat.h
2048 @comment GNU
2049 @deftypefn Macro int S_ISSOCK (mode_t @var{m})
2050 This macro returns non-zero if the file is a socket.  @xref{Sockets}.
2051 @end deftypefn
2053 An alternate non-POSIX method of testing the file type is supported for
2054 compatibility with BSD.  The mode can be bitwise AND-ed with
2055 @code{S_IFMT} to extract the file type code, and compared to the
2056 appropriate constant.  For example,
2058 @smallexample
2059 S_ISCHR (@var{mode})
2060 @end smallexample
2062 @noindent
2063 is equivalent to:
2065 @smallexample
2066 ((@var{mode} & S_IFMT) == S_IFCHR)
2067 @end smallexample
2069 @comment sys/stat.h
2070 @comment BSD
2071 @deftypevr Macro int S_IFMT
2072 This is a bit mask used to extract the file type code from a mode value.
2073 @end deftypevr
2075 These are the symbolic names for the different file type codes:
2077 @table @code
2078 @comment sys/stat.h
2079 @comment BSD
2080 @item S_IFDIR
2081 @vindex S_IFDIR
2082 This is the file type constant of a directory file.
2084 @comment sys/stat.h
2085 @comment BSD
2086 @item S_IFCHR
2087 @vindex S_IFCHR
2088 This is the file type constant of a character-oriented device file.
2090 @comment sys/stat.h
2091 @comment BSD
2092 @item S_IFBLK
2093 @vindex S_IFBLK
2094 This is the file type constant of a block-oriented device file.
2096 @comment sys/stat.h
2097 @comment BSD
2098 @item S_IFREG
2099 @vindex S_IFREG
2100 This is the file type constant of a regular file.
2102 @comment sys/stat.h
2103 @comment BSD
2104 @item S_IFLNK
2105 @vindex S_IFLNK
2106 This is the file type constant of a symbolic link.
2108 @comment sys/stat.h
2109 @comment BSD
2110 @item S_IFSOCK
2111 @vindex S_IFSOCK
2112 This is the file type constant of a socket.
2114 @comment sys/stat.h
2115 @comment BSD
2116 @item S_IFIFO
2117 @vindex S_IFIFO
2118 This is the file type constant of a FIFO or pipe.
2119 @end table
2121 The POSIX.1b standard introduced a few more objects which possibly can
2122 be implemented as object in the filesystem.  These are message queues,
2123 semaphores, and shared memory objects.  To allow differentiating these
2124 objects from other files the POSIX standard introduces three new test
2125 macros.  But unlike the other macros it does not take the value of the
2126 @code{st_mode} field as the parameter.  Instead they expect a pointer to
2127 the whole @code{struct stat} structure.
2129 @comment sys/stat.h
2130 @comment POSIX
2131 @deftypefn Macro int S_TYPEISMQ (struct stat *@var{s})
2132 If the system implement POSIX message queues as distinct objects and the
2133 file is a message queue object, this macro returns a non-zero value.
2134 In all other cases the result is zero.
2135 @end deftypefn
2137 @comment sys/stat.h
2138 @comment POSIX
2139 @deftypefn Macro int S_TYPEISSEM (struct stat *@var{s})
2140 If the system implement POSIX semaphores as distinct objects and the
2141 file is a semaphore object, this macro returns a non-zero value.
2142 In all other cases the result is zero.
2143 @end deftypefn
2145 @comment sys/stat.h
2146 @comment POSIX
2147 @deftypefn Macro int S_TYPEISSHM (struct stat *@var{s})
2148 If the system implement POSIX shared memory objects as distinct objects
2149 and the file is an shared memory object, this macro returns a non-zero
2150 value.  In all other cases the result is zero.
2151 @end deftypefn
2153 @node File Owner
2154 @subsection File Owner
2155 @cindex file owner
2156 @cindex owner of a file
2157 @cindex group owner of a file
2159 Every file has an @dfn{owner} which is one of the registered user names
2160 defined on the system.  Each file also has a @dfn{group} which is one of
2161 the defined groups.  The file owner can often be useful for showing you
2162 who edited the file (especially when you edit with GNU Emacs), but its
2163 main purpose is for access control.
2165 The file owner and group play a role in determining access because the
2166 file has one set of access permission bits for the owner, another set
2167 that applies to users who belong to the file's group, and a third set of
2168 bits that applies to everyone else.  @xref{Access Permission}, for the
2169 details of how access is decided based on this data.
2171 When a file is created, its owner is set to the effective user ID of the
2172 process that creates it (@pxref{Process Persona}).  The file's group ID
2173 may be set to either the effective group ID of the process, or the group
2174 ID of the directory that contains the file, depending on the system
2175 where the file is stored.  When you access a remote file system, it
2176 behaves according to its own rules, not according to the system your
2177 program is running on.  Thus, your program must be prepared to encounter
2178 either kind of behavior no matter what kind of system you run it on.
2180 @pindex chown
2181 @pindex chgrp
2182 You can change the owner and/or group owner of an existing file using
2183 the @code{chown} function.  This is the primitive for the @code{chown}
2184 and @code{chgrp} shell commands.
2186 @pindex unistd.h
2187 The prototype for this function is declared in @file{unistd.h}.
2189 @comment unistd.h
2190 @comment POSIX.1
2191 @deftypefun int chown (const char *@var{filename}, uid_t @var{owner}, gid_t @var{group})
2192 The @code{chown} function changes the owner of the file @var{filename} to
2193 @var{owner}, and its group owner to @var{group}.
2195 Changing the owner of the file on certain systems clears the set-user-ID
2196 and set-group-ID permission bits.  (This is because those bits may not
2197 be appropriate for the new owner.)  Other file permission bits are not
2198 changed.
2200 The return value is @code{0} on success and @code{-1} on failure.
2201 In addition to the usual file name errors (@pxref{File Name Errors}),
2202 the following @code{errno} error conditions are defined for this function:
2204 @table @code
2205 @item EPERM
2206 This process lacks permission to make the requested change.
2208 Only privileged users or the file's owner can change the file's group.
2209 On most file systems, only privileged users can change the file owner;
2210 some file systems allow you to change the owner if you are currently the
2211 owner.  When you access a remote file system, the behavior you encounter
2212 is determined by the system that actually holds the file, not by the
2213 system your program is running on.
2215 @xref{Options for Files}, for information about the
2216 @code{_POSIX_CHOWN_RESTRICTED} macro.
2218 @item EROFS
2219 The file is on a read-only file system.
2220 @end table
2221 @end deftypefun
2223 @comment unistd.h
2224 @comment BSD
2225 @deftypefun int fchown (int @var{filedes}, uid_t @var{owner}, gid_t @var{group})
2226 This is like @code{chown}, except that it changes the owner of the open
2227 file with descriptor @var{filedes}.
2229 The return value from @code{fchown} is @code{0} on success and @code{-1}
2230 on failure.  The following @code{errno} error codes are defined for this
2231 function:
2233 @table @code
2234 @item EBADF
2235 The @var{filedes} argument is not a valid file descriptor.
2237 @item EINVAL
2238 The @var{filedes} argument corresponds to a pipe or socket, not an ordinary
2239 file.
2241 @item EPERM
2242 This process lacks permission to make the requested change.  For details
2243 see @code{chmod} above.
2245 @item EROFS
2246 The file resides on a read-only file system.
2247 @end table
2248 @end deftypefun
2250 @node Permission Bits
2251 @subsection The Mode Bits for Access Permission
2253 The @dfn{file mode}, stored in the @code{st_mode} field of the file
2254 attributes, contains two kinds of information: the file type code, and
2255 the access permission bits.  This section discusses only the access
2256 permission bits, which control who can read or write the file.
2257 @xref{Testing File Type}, for information about the file type code.
2259 All of the symbols listed in this section are defined in the header file
2260 @file{sys/stat.h}.
2261 @pindex sys/stat.h
2263 @cindex file permission bits
2264 These symbolic constants are defined for the file mode bits that control
2265 access permission for the file:
2267 @table @code
2268 @comment sys/stat.h
2269 @comment POSIX.1
2270 @item S_IRUSR
2271 @vindex S_IRUSR
2272 @comment sys/stat.h
2273 @comment BSD
2274 @itemx S_IREAD
2275 @vindex S_IREAD
2276 Read permission bit for the owner of the file.  On many systems this bit
2277 is 0400.  @code{S_IREAD} is an obsolete synonym provided for BSD
2278 compatibility.
2280 @comment sys/stat.h
2281 @comment POSIX.1
2282 @item S_IWUSR
2283 @vindex S_IWUSR
2284 @comment sys/stat.h
2285 @comment BSD
2286 @itemx S_IWRITE
2287 @vindex S_IWRITE
2288 Write permission bit for the owner of the file.  Usually 0200.
2289 @w{@code{S_IWRITE}} is an obsolete synonym provided for BSD compatibility.
2291 @comment sys/stat.h
2292 @comment POSIX.1
2293 @item S_IXUSR
2294 @vindex S_IXUSR
2295 @comment sys/stat.h
2296 @comment BSD
2297 @itemx S_IEXEC
2298 @vindex S_IEXEC
2299 Execute (for ordinary files) or search (for directories) permission bit
2300 for the owner of the file.  Usually 0100.  @code{S_IEXEC} is an obsolete
2301 synonym provided for BSD compatibility.
2303 @comment sys/stat.h
2304 @comment POSIX.1
2305 @item S_IRWXU
2306 @vindex S_IRWXU
2307 This is equivalent to @samp{(S_IRUSR | S_IWUSR | S_IXUSR)}.
2309 @comment sys/stat.h
2310 @comment POSIX.1
2311 @item S_IRGRP
2312 @vindex S_IRGRP
2313 Read permission bit for the group owner of the file.  Usually 040.
2315 @comment sys/stat.h
2316 @comment POSIX.1
2317 @item S_IWGRP
2318 @vindex S_IWGRP
2319 Write permission bit for the group owner of the file.  Usually 020.
2321 @comment sys/stat.h
2322 @comment POSIX.1
2323 @item S_IXGRP
2324 @vindex S_IXGRP
2325 Execute or search permission bit for the group owner of the file.
2326 Usually 010.
2328 @comment sys/stat.h
2329 @comment POSIX.1
2330 @item S_IRWXG
2331 @vindex S_IRWXG
2332 This is equivalent to @samp{(S_IRGRP | S_IWGRP | S_IXGRP)}.
2334 @comment sys/stat.h
2335 @comment POSIX.1
2336 @item S_IROTH
2337 @vindex S_IROTH
2338 Read permission bit for other users.  Usually 04.
2340 @comment sys/stat.h
2341 @comment POSIX.1
2342 @item S_IWOTH
2343 @vindex S_IWOTH
2344 Write permission bit for other users.  Usually 02.
2346 @comment sys/stat.h
2347 @comment POSIX.1
2348 @item S_IXOTH
2349 @vindex S_IXOTH
2350 Execute or search permission bit for other users.  Usually 01.
2352 @comment sys/stat.h
2353 @comment POSIX.1
2354 @item S_IRWXO
2355 @vindex S_IRWXO
2356 This is equivalent to @samp{(S_IROTH | S_IWOTH | S_IXOTH)}.
2358 @comment sys/stat.h
2359 @comment POSIX
2360 @item S_ISUID
2361 @vindex S_ISUID
2362 This is the set-user-ID on execute bit, usually 04000.
2363 @xref{How Change Persona}.
2365 @comment sys/stat.h
2366 @comment POSIX
2367 @item S_ISGID
2368 @vindex S_ISGID
2369 This is the set-group-ID on execute bit, usually 02000.
2370 @xref{How Change Persona}.
2372 @cindex sticky bit
2373 @comment sys/stat.h
2374 @comment BSD
2375 @item S_ISVTX
2376 @vindex S_ISVTX
2377 This is the @dfn{sticky} bit, usually 01000.
2379 For a directory it gives permission to delete a file in that directory
2380 only if you own that file.  Ordinarily, a user can either delete all the
2381 files in a directory or cannot delete any of them (based on whether the
2382 user has write permission for the directory).  The same restriction
2383 applies---you must have both write permission for the directory and own
2384 the file you want to delete.  The one exception is that the owner of the
2385 directory can delete any file in the directory, no matter who owns it
2386 (provided the owner has given himself write permission for the
2387 directory).  This is commonly used for the @file{/tmp} directory, where
2388 anyone may create files but not delete files created by other users.
2390 Originally the sticky bit on an executable file modified the swapping
2391 policies of the system.  Normally, when a program terminated, its pages
2392 in core were immediately freed and reused.  If the sticky bit was set on
2393 the executable file, the system kept the pages in core for a while as if
2394 the program were still running.  This was advantageous for a program
2395 likely to be run many times in succession.  This usage is obsolete in
2396 modern systems.  When a program terminates, its pages always remain in
2397 core as long as there is no shortage of memory in the system.  When the
2398 program is next run, its pages will still be in core if no shortage
2399 arose since the last run.
2401 On some modern systems where the sticky bit has no useful meaning for an
2402 executable file, you cannot set the bit at all for a non-directory.
2403 If you try, @code{chmod} fails with @code{EFTYPE};
2404 @pxref{Setting Permissions}.
2406 Some systems (particularly SunOS) have yet another use for the sticky
2407 bit.  If the sticky bit is set on a file that is @emph{not} executable,
2408 it means the opposite: never cache the pages of this file at all.  The
2409 main use of this is for the files on an NFS server machine which are
2410 used as the swap area of diskless client machines.  The idea is that the
2411 pages of the file will be cached in the client's memory, so it is a
2412 waste of the server's memory to cache them a second time.  With this
2413 usage the sticky bit also implies that the filesystem may fail to record
2414 the file's modification time onto disk reliably (the idea being that
2415 no-one cares for a swap file).
2417 This bit is only available on BSD systems (and those derived from
2418 them).  Therefore one has to use the @code{_BSD_SOURCE} feature select
2419 macro to get the definition (@pxref{Feature Test Macros}).
2420 @end table
2422 The actual bit values of the symbols are listed in the table above
2423 so you can decode file mode values when debugging your programs.
2424 These bit values are correct for most systems, but they are not
2425 guaranteed.
2427 @strong{Warning:} Writing explicit numbers for file permissions is bad
2428 practice.  Not only is it not portable, it also requires everyone who
2429 reads your program to remember what the bits mean.  To make your program
2430 clean use the symbolic names.
2432 @node Access Permission
2433 @subsection How Your Access to a File is Decided
2434 @cindex permission to access a file
2435 @cindex access permission for a file
2436 @cindex file access permission
2438 Recall that the operating system normally decides access permission for
2439 a file based on the effective user and group IDs of the process and its
2440 supplementary group IDs, together with the file's owner, group and
2441 permission bits.  These concepts are discussed in detail in @ref{Process
2442 Persona}.
2444 If the effective user ID of the process matches the owner user ID of the
2445 file, then permissions for read, write, and execute/search are
2446 controlled by the corresponding ``user'' (or ``owner'') bits.  Likewise,
2447 if any of the effective group ID or supplementary group IDs of the
2448 process matches the group owner ID of the file, then permissions are
2449 controlled by the ``group'' bits.  Otherwise, permissions are controlled
2450 by the ``other'' bits.
2452 Privileged users, like @samp{root}, can access any file regardless of
2453 its permission bits.  As a special case, for a file to be executable
2454 even by a privileged user, at least one of its execute bits must be set.
2456 @node Setting Permissions
2457 @subsection Assigning File Permissions
2459 @cindex file creation mask
2460 @cindex umask
2461 The primitive functions for creating files (for example, @code{open} or
2462 @code{mkdir}) take a @var{mode} argument, which specifies the file
2463 permissions to give the newly created file.  This mode is modified by
2464 the process's @dfn{file creation mask}, or @dfn{umask}, before it is
2465 used.
2467 The bits that are set in the file creation mask identify permissions
2468 that are always to be disabled for newly created files.  For example, if
2469 you set all the ``other'' access bits in the mask, then newly created
2470 files are not accessible at all to processes in the ``other'' category,
2471 even if the @var{mode} argument passed to the create function would
2472 permit such access.  In other words, the file creation mask is the
2473 complement of the ordinary access permissions you want to grant.
2475 Programs that create files typically specify a @var{mode} argument that
2476 includes all the permissions that make sense for the particular file.
2477 For an ordinary file, this is typically read and write permission for
2478 all classes of users.  These permissions are then restricted as
2479 specified by the individual user's own file creation mask.
2481 @findex chmod
2482 To change the permission of an existing file given its name, call
2483 @code{chmod}.  This function uses the specified permission bits and
2484 ignores the file creation mask.
2486 @pindex umask
2487 In normal use, the file creation mask is initialized by the user's login
2488 shell (using the @code{umask} shell command), and inherited by all
2489 subprocesses.  Application programs normally don't need to worry about
2490 the file creation mask.  It will automatically do what it is supposed to
2493 When your program needs to create a file and bypass the umask for its
2494 access permissions, the easiest way to do this is to use @code{fchmod}
2495 after opening the file, rather than changing the umask.  In fact,
2496 changing the umask is usually done only by shells.  They use the
2497 @code{umask} function.
2499 The functions in this section are declared in @file{sys/stat.h}.
2500 @pindex sys/stat.h
2502 @comment sys/stat.h
2503 @comment POSIX.1
2504 @deftypefun mode_t umask (mode_t @var{mask})
2505 The @code{umask} function sets the file creation mask of the current
2506 process to @var{mask}, and returns the previous value of the file
2507 creation mask.
2509 Here is an example showing how to read the mask with @code{umask}
2510 without changing it permanently:
2512 @smallexample
2513 mode_t
2514 read_umask (void)
2516   mode_t mask = umask (0);
2517   umask (mask);
2518   return mask;
2520 @end smallexample
2522 @noindent
2523 However, on @gnuhurdsystems{} it is better to use @code{getumask} if
2524 you just want to read the mask value, because it is reentrant.
2525 @end deftypefun
2527 @comment sys/stat.h
2528 @comment GNU
2529 @deftypefun mode_t getumask (void)
2530 Return the current value of the file creation mask for the current
2531 process.  This function is a GNU extension and is only available on
2532 @gnuhurdsystems{}.
2533 @end deftypefun
2535 @comment sys/stat.h
2536 @comment POSIX.1
2537 @deftypefun int chmod (const char *@var{filename}, mode_t @var{mode})
2538 The @code{chmod} function sets the access permission bits for the file
2539 named by @var{filename} to @var{mode}.
2541 If @var{filename} is a symbolic link, @code{chmod} changes the
2542 permissions of the file pointed to by the link, not those of the link
2543 itself.
2545 This function returns @code{0} if successful and @code{-1} if not.  In
2546 addition to the usual file name errors (@pxref{File Name
2547 Errors}), the following @code{errno} error conditions are defined for
2548 this function:
2550 @table @code
2551 @item ENOENT
2552 The named file doesn't exist.
2554 @item EPERM
2555 This process does not have permission to change the access permissions
2556 of this file.  Only the file's owner (as judged by the effective user ID
2557 of the process) or a privileged user can change them.
2559 @item EROFS
2560 The file resides on a read-only file system.
2562 @item EFTYPE
2563 @var{mode} has the @code{S_ISVTX} bit (the ``sticky bit'') set,
2564 and the named file is not a directory.  Some systems do not allow setting the
2565 sticky bit on non-directory files, and some do (and only some of those
2566 assign a useful meaning to the bit for non-directory files).
2568 You only get @code{EFTYPE} on systems where the sticky bit has no useful
2569 meaning for non-directory files, so it is always safe to just clear the
2570 bit in @var{mode} and call @code{chmod} again.  @xref{Permission Bits},
2571 for full details on the sticky bit.
2572 @end table
2573 @end deftypefun
2575 @comment sys/stat.h
2576 @comment BSD
2577 @deftypefun int fchmod (int @var{filedes}, mode_t @var{mode})
2578 This is like @code{chmod}, except that it changes the permissions of the
2579 currently open file given by @var{filedes}.
2581 The return value from @code{fchmod} is @code{0} on success and @code{-1}
2582 on failure.  The following @code{errno} error codes are defined for this
2583 function:
2585 @table @code
2586 @item EBADF
2587 The @var{filedes} argument is not a valid file descriptor.
2589 @item EINVAL
2590 The @var{filedes} argument corresponds to a pipe or socket, or something
2591 else that doesn't really have access permissions.
2593 @item EPERM
2594 This process does not have permission to change the access permissions
2595 of this file.  Only the file's owner (as judged by the effective user ID
2596 of the process) or a privileged user can change them.
2598 @item EROFS
2599 The file resides on a read-only file system.
2600 @end table
2601 @end deftypefun
2603 @node Testing File Access
2604 @subsection Testing Permission to Access a File
2605 @cindex testing access permission
2606 @cindex access, testing for
2607 @cindex setuid programs and file access
2609 In some situations it is desirable to allow programs to access files or
2610 devices even if this is not possible with the permissions granted to the
2611 user.  One possible solution is to set the setuid-bit of the program
2612 file.  If such a program is started the @emph{effective} user ID of the
2613 process is changed to that of the owner of the program file.  So to
2614 allow write access to files like @file{/etc/passwd}, which normally can
2615 be written only by the super-user, the modifying program will have to be
2616 owned by @code{root} and the setuid-bit must be set.
2618 But beside the files the program is intended to change the user should
2619 not be allowed to access any file to which s/he would not have access
2620 anyway.  The program therefore must explicitly check whether @emph{the
2621 user} would have the necessary access to a file, before it reads or
2622 writes the file.
2624 To do this, use the function @code{access}, which checks for access
2625 permission based on the process's @emph{real} user ID rather than the
2626 effective user ID.  (The setuid feature does not alter the real user ID,
2627 so it reflects the user who actually ran the program.)
2629 There is another way you could check this access, which is easy to
2630 describe, but very hard to use.  This is to examine the file mode bits
2631 and mimic the system's own access computation.  This method is
2632 undesirable because many systems have additional access control
2633 features; your program cannot portably mimic them, and you would not
2634 want to try to keep track of the diverse features that different systems
2635 have.  Using @code{access} is simple and automatically does whatever is
2636 appropriate for the system you are using.
2638 @code{access} is @emph{only} only appropriate to use in setuid programs.
2639 A non-setuid program will always use the effective ID rather than the
2640 real ID.
2642 @pindex unistd.h
2643 The symbols in this section are declared in @file{unistd.h}.
2645 @comment unistd.h
2646 @comment POSIX.1
2647 @deftypefun int access (const char *@var{filename}, int @var{how})
2648 The @code{access} function checks to see whether the file named by
2649 @var{filename} can be accessed in the way specified by the @var{how}
2650 argument.  The @var{how} argument either can be the bitwise OR of the
2651 flags @code{R_OK}, @code{W_OK}, @code{X_OK}, or the existence test
2652 @code{F_OK}.
2654 This function uses the @emph{real} user and group IDs of the calling
2655 process, rather than the @emph{effective} IDs, to check for access
2656 permission.  As a result, if you use the function from a @code{setuid}
2657 or @code{setgid} program (@pxref{How Change Persona}), it gives
2658 information relative to the user who actually ran the program.
2660 The return value is @code{0} if the access is permitted, and @code{-1}
2661 otherwise.  (In other words, treated as a predicate function,
2662 @code{access} returns true if the requested access is @emph{denied}.)
2664 In addition to the usual file name errors (@pxref{File Name
2665 Errors}), the following @code{errno} error conditions are defined for
2666 this function:
2668 @table @code
2669 @item EACCES
2670 The access specified by @var{how} is denied.
2672 @item ENOENT
2673 The file doesn't exist.
2675 @item EROFS
2676 Write permission was requested for a file on a read-only file system.
2677 @end table
2678 @end deftypefun
2680 These macros are defined in the header file @file{unistd.h} for use
2681 as the @var{how} argument to the @code{access} function.  The values
2682 are integer constants.
2683 @pindex unistd.h
2685 @comment unistd.h
2686 @comment POSIX.1
2687 @deftypevr Macro int R_OK
2688 Flag meaning test for read permission.
2689 @end deftypevr
2691 @comment unistd.h
2692 @comment POSIX.1
2693 @deftypevr Macro int W_OK
2694 Flag meaning test for write permission.
2695 @end deftypevr
2697 @comment unistd.h
2698 @comment POSIX.1
2699 @deftypevr Macro int X_OK
2700 Flag meaning test for execute/search permission.
2701 @end deftypevr
2703 @comment unistd.h
2704 @comment POSIX.1
2705 @deftypevr Macro int F_OK
2706 Flag meaning test for existence of the file.
2707 @end deftypevr
2709 @node File Times
2710 @subsection File Times
2712 @cindex file access time
2713 @cindex file modification time
2714 @cindex file attribute modification time
2715 Each file has three time stamps associated with it:  its access time,
2716 its modification time, and its attribute modification time.  These
2717 correspond to the @code{st_atime}, @code{st_mtime}, and @code{st_ctime}
2718 members of the @code{stat} structure; see @ref{File Attributes}.
2720 All of these times are represented in calendar time format, as
2721 @code{time_t} objects.  This data type is defined in @file{time.h}.
2722 For more information about representation and manipulation of time
2723 values, see @ref{Calendar Time}.
2724 @pindex time.h
2726 Reading from a file updates its access time attribute, and writing
2727 updates its modification time.  When a file is created, all three
2728 time stamps for that file are set to the current time.  In addition, the
2729 attribute change time and modification time fields of the directory that
2730 contains the new entry are updated.
2732 Adding a new name for a file with the @code{link} function updates the
2733 attribute change time field of the file being linked, and both the
2734 attribute change time and modification time fields of the directory
2735 containing the new name.  These same fields are affected if a file name
2736 is deleted with @code{unlink}, @code{remove} or @code{rmdir}.  Renaming
2737 a file with @code{rename} affects only the attribute change time and
2738 modification time fields of the two parent directories involved, and not
2739 the times for the file being renamed.
2741 Changing the attributes of a file (for example, with @code{chmod})
2742 updates its attribute change time field.
2744 You can also change some of the time stamps of a file explicitly using
2745 the @code{utime} function---all except the attribute change time.  You
2746 need to include the header file @file{utime.h} to use this facility.
2747 @pindex utime.h
2749 @comment utime.h
2750 @comment POSIX.1
2751 @deftp {Data Type} {struct utimbuf}
2752 The @code{utimbuf} structure is used with the @code{utime} function to
2753 specify new access and modification times for a file.  It contains the
2754 following members:
2756 @table @code
2757 @item time_t actime
2758 This is the access time for the file.
2760 @item time_t modtime
2761 This is the modification time for the file.
2762 @end table
2763 @end deftp
2765 @comment utime.h
2766 @comment POSIX.1
2767 @deftypefun int utime (const char *@var{filename}, const struct utimbuf *@var{times})
2768 This function is used to modify the file times associated with the file
2769 named @var{filename}.
2771 If @var{times} is a null pointer, then the access and modification times
2772 of the file are set to the current time.  Otherwise, they are set to the
2773 values from the @code{actime} and @code{modtime} members (respectively)
2774 of the @code{utimbuf} structure pointed to by @var{times}.
2776 The attribute modification time for the file is set to the current time
2777 in either case (since changing the time stamps is itself a modification
2778 of the file attributes).
2780 The @code{utime} function returns @code{0} if successful and @code{-1}
2781 on failure.  In addition to the usual file name errors
2782 (@pxref{File Name Errors}), the following @code{errno} error conditions
2783 are defined for this function:
2785 @table @code
2786 @item EACCES
2787 There is a permission problem in the case where a null pointer was
2788 passed as the @var{times} argument.  In order to update the time stamp on
2789 the file, you must either be the owner of the file, have write
2790 permission for the file, or be a privileged user.
2792 @item ENOENT
2793 The file doesn't exist.
2795 @item EPERM
2796 If the @var{times} argument is not a null pointer, you must either be
2797 the owner of the file or be a privileged user.
2799 @item EROFS
2800 The file lives on a read-only file system.
2801 @end table
2802 @end deftypefun
2804 Each of the three time stamps has a corresponding microsecond part,
2805 which extends its resolution.  These fields are called
2806 @code{st_atime_usec}, @code{st_mtime_usec}, and @code{st_ctime_usec};
2807 each has a value between 0 and 999,999, which indicates the time in
2808 microseconds.  They correspond to the @code{tv_usec} field of a
2809 @code{timeval} structure; see @ref{High-Resolution Calendar}.
2811 The @code{utimes} function is like @code{utime}, but also lets you specify
2812 the fractional part of the file times.  The prototype for this function is
2813 in the header file @file{sys/time.h}.
2814 @pindex sys/time.h
2816 @comment sys/time.h
2817 @comment BSD
2818 @deftypefun int utimes (const char *@var{filename}, const struct timeval @var{tvp}@t{[2]})
2819 This function sets the file access and modification times of the file
2820 @var{filename}.  The new file access time is specified by
2821 @code{@var{tvp}[0]}, and the new modification time by
2822 @code{@var{tvp}[1]}.  Similar to @code{utime}, if @var{tvp} is a null
2823 pointer then the access and modification times of the file are set to
2824 the current time.  This function comes from BSD.
2826 The return values and error conditions are the same as for the @code{utime}
2827 function.
2828 @end deftypefun
2830 @comment sys/time.h
2831 @comment BSD
2832 @deftypefun int lutimes (const char *@var{filename}, const struct timeval @var{tvp}@t{[2]})
2833 This function is like @code{utimes}, except that it does not follow
2834 symbolic links.  If @var{filename} is the name of a symbolic link,
2835 @code{lutimes} sets the file access and modification times of the
2836 symbolic link special file itself (as seen by @code{lstat};
2837 @pxref{Symbolic Links}) while @code{utimes} sets the file access and
2838 modification times of the file the symbolic link refers to.  This
2839 function comes from FreeBSD, and is not available on all platforms (if
2840 not available, it will fail with @code{ENOSYS}).
2842 The return values and error conditions are the same as for the @code{utime}
2843 function.
2844 @end deftypefun
2846 @comment sys/time.h
2847 @comment BSD
2848 @deftypefun int futimes (int @var{fd}, const struct timeval @var{tvp}@t{[2]})
2849 This function is like @code{utimes}, except that it takes an open file
2850 descriptor as an argument instead of a file name.  @xref{Low-Level
2851 I/O}.  This function comes from FreeBSD, and is not available on all
2852 platforms (if not available, it will fail with @code{ENOSYS}).
2854 Like @code{utimes}, @code{futimes} returns @code{0} on success and @code{-1}
2855 on failure.  The following @code{errno} error conditions are defined for
2856 @code{futimes}:
2858 @table @code
2859 @item EACCES
2860 There is a permission problem in the case where a null pointer was
2861 passed as the @var{times} argument.  In order to update the time stamp on
2862 the file, you must either be the owner of the file, have write
2863 permission for the file, or be a privileged user.
2865 @item EBADF
2866 The @var{filedes} argument is not a valid file descriptor.
2868 @item EPERM
2869 If the @var{times} argument is not a null pointer, you must either be
2870 the owner of the file or be a privileged user.
2872 @item EROFS
2873 The file lives on a read-only file system.
2874 @end table
2875 @end deftypefun
2877 @node File Size
2878 @subsection File Size
2880 Normally file sizes are maintained automatically.  A file begins with a
2881 size of @math{0} and is automatically extended when data is written past
2882 its end.  It is also possible to empty a file completely by an
2883 @code{open} or @code{fopen} call.
2885 However, sometimes it is necessary to @emph{reduce} the size of a file.
2886 This can be done with the @code{truncate} and @code{ftruncate} functions.
2887 They were introduced in BSD Unix.  @code{ftruncate} was later added to
2888 POSIX.1.
2890 Some systems allow you to extend a file (creating holes) with these
2891 functions.  This is useful when using memory-mapped I/O
2892 (@pxref{Memory-mapped I/O}), where files are not automatically extended.
2893 However, it is not portable but must be implemented if @code{mmap}
2894 allows mapping of files (i.e., @code{_POSIX_MAPPED_FILES} is defined).
2896 Using these functions on anything other than a regular file gives
2897 @emph{undefined} results.  On many systems, such a call will appear to
2898 succeed, without actually accomplishing anything.
2900 @comment unistd.h
2901 @comment X/Open
2902 @deftypefun int truncate (const char *@var{filename}, off_t @var{length})
2904 The @code{truncate} function changes the size of @var{filename} to
2905 @var{length}.  If @var{length} is shorter than the previous length, data
2906 at the end will be lost.  The file must be writable by the user to
2907 perform this operation.
2909 If @var{length} is longer, holes will be added to the end.  However, some
2910 systems do not support this feature and will leave the file unchanged.
2912 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
2913 @code{truncate} function is in fact @code{truncate64} and the type
2914 @code{off_t} has 64 bits which makes it possible to handle files up to
2915 @math{2^63} bytes in length.
2917 The return value is @math{0} for success, or @math{-1} for an error.  In
2918 addition to the usual file name errors, the following errors may occur:
2920 @table @code
2922 @item EACCES
2923 The file is a directory or not writable.
2925 @item EINVAL
2926 @var{length} is negative.
2928 @item EFBIG
2929 The operation would extend the file beyond the limits of the operating system.
2931 @item EIO
2932 A hardware I/O error occurred.
2934 @item EPERM
2935 The file is "append-only" or "immutable".
2937 @item EINTR
2938 The operation was interrupted by a signal.
2940 @end table
2942 @end deftypefun
2944 @comment unistd.h
2945 @comment Unix98
2946 @deftypefun int truncate64 (const char *@var{name}, off64_t @var{length})
2947 This function is similar to the @code{truncate} function.  The
2948 difference is that the @var{length} argument is 64 bits wide even on 32
2949 bits machines, which allows the handling of files with sizes up to
2950 @math{2^63} bytes.
2952 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
2953 32 bits machine this function is actually available under the name
2954 @code{truncate} and so transparently replaces the 32 bits interface.
2955 @end deftypefun
2957 @comment unistd.h
2958 @comment POSIX
2959 @deftypefun int ftruncate (int @var{fd}, off_t @var{length})
2961 This is like @code{truncate}, but it works on a file descriptor @var{fd}
2962 for an opened file instead of a file name to identify the object.  The
2963 file must be opened for writing to successfully carry out the operation.
2965 The POSIX standard leaves it implementation defined what happens if the
2966 specified new @var{length} of the file is bigger than the original size.
2967 The @code{ftruncate} function might simply leave the file alone and do
2968 nothing or it can increase the size to the desired size.  In this later
2969 case the extended area should be zero-filled.  So using @code{ftruncate}
2970 is no reliable way to increase the file size but if it is possible it is
2971 probably the fastest way.  The function also operates on POSIX shared
2972 memory segments if these are implemented by the system.
2974 @code{ftruncate} is especially useful in combination with @code{mmap}.
2975 Since the mapped region must have a fixed size one cannot enlarge the
2976 file by writing something beyond the last mapped page.  Instead one has
2977 to enlarge the file itself and then remap the file with the new size.
2978 The example below shows how this works.
2980 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
2981 @code{ftruncate} function is in fact @code{ftruncate64} and the type
2982 @code{off_t} has 64 bits which makes it possible to handle files up to
2983 @math{2^63} bytes in length.
2985 The return value is @math{0} for success, or @math{-1} for an error.  The
2986 following errors may occur:
2988 @table @code
2990 @item EBADF
2991 @var{fd} does not correspond to an open file.
2993 @item EACCES
2994 @var{fd} is a directory or not open for writing.
2996 @item EINVAL
2997 @var{length} is negative.
2999 @item EFBIG
3000 The operation would extend the file beyond the limits of the operating system.
3001 @c or the open() call -- with the not-yet-discussed feature of opening
3002 @c files with extra-large offsets.
3004 @item EIO
3005 A hardware I/O error occurred.
3007 @item EPERM
3008 The file is "append-only" or "immutable".
3010 @item EINTR
3011 The operation was interrupted by a signal.
3013 @c ENOENT is also possible on Linux --- however it only occurs if the file
3014 @c descriptor has a `file' structure but no `inode' structure.  I'm not
3015 @c sure how such an fd could be created.  Perhaps it's a bug.
3017 @end table
3019 @end deftypefun
3021 @comment unistd.h
3022 @comment Unix98
3023 @deftypefun int ftruncate64 (int @var{id}, off64_t @var{length})
3024 This function is similar to the @code{ftruncate} function.  The
3025 difference is that the @var{length} argument is 64 bits wide even on 32
3026 bits machines which allows the handling of files with sizes up to
3027 @math{2^63} bytes.
3029 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
3030 32 bits machine this function is actually available under the name
3031 @code{ftruncate} and so transparently replaces the 32 bits interface.
3032 @end deftypefun
3034 As announced here is a little example of how to use @code{ftruncate} in
3035 combination with @code{mmap}:
3037 @smallexample
3038 int fd;
3039 void *start;
3040 size_t len;
3043 add (off_t at, void *block, size_t size)
3045   if (at + size > len)
3046     @{
3047       /* Resize the file and remap.  */
3048       size_t ps = sysconf (_SC_PAGESIZE);
3049       size_t ns = (at + size + ps - 1) & ~(ps - 1);
3050       void *np;
3051       if (ftruncate (fd, ns) < 0)
3052         return -1;
3053       np = mmap (NULL, ns, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
3054       if (np == MAP_FAILED)
3055         return -1;
3056       start = np;
3057       len = ns;
3058     @}
3059   memcpy ((char *) start + at, block, size);
3060   return 0;
3062 @end smallexample
3064 The function @code{add} writes a block of memory at an arbitrary
3065 position in the file.  If the current size of the file is too small it
3066 is extended.  Note the it is extended by a round number of pages.  This
3067 is a requirement of @code{mmap}.  The program has to keep track of the
3068 real size, and when it has finished a final @code{ftruncate} call should
3069 set the real size of the file.
3071 @node Making Special Files
3072 @section Making Special Files
3073 @cindex creating special files
3074 @cindex special files
3076 The @code{mknod} function is the primitive for making special files,
3077 such as files that correspond to devices.  @Theglibc{} includes
3078 this function for compatibility with BSD.
3080 The prototype for @code{mknod} is declared in @file{sys/stat.h}.
3081 @pindex sys/stat.h
3083 @comment sys/stat.h
3084 @comment BSD
3085 @deftypefun int mknod (const char *@var{filename}, mode_t @var{mode}, dev_t @var{dev})
3086 The @code{mknod} function makes a special file with name @var{filename}.
3087 The @var{mode} specifies the mode of the file, and may include the various
3088 special file bits, such as @code{S_IFCHR} (for a character special file)
3089 or @code{S_IFBLK} (for a block special file).  @xref{Testing File Type}.
3091 The @var{dev} argument specifies which device the special file refers to.
3092 Its exact interpretation depends on the kind of special file being created.
3094 The return value is @code{0} on success and @code{-1} on error.  In addition
3095 to the usual file name errors (@pxref{File Name Errors}), the
3096 following @code{errno} error conditions are defined for this function:
3098 @table @code
3099 @item EPERM
3100 The calling process is not privileged.  Only the superuser can create
3101 special files.
3103 @item ENOSPC
3104 The directory or file system that would contain the new file is full
3105 and cannot be extended.
3107 @item EROFS
3108 The directory containing the new file can't be modified because it's on
3109 a read-only file system.
3111 @item EEXIST
3112 There is already a file named @var{filename}.  If you want to replace
3113 this file, you must remove the old file explicitly first.
3114 @end table
3115 @end deftypefun
3117 @node Temporary Files
3118 @section Temporary Files
3120 If you need to use a temporary file in your program, you can use the
3121 @code{tmpfile} function to open it.  Or you can use the @code{tmpnam}
3122 (better: @code{tmpnam_r}) function to provide a name for a temporary
3123 file and then you can open it in the usual way with @code{fopen}.
3125 The @code{tempnam} function is like @code{tmpnam} but lets you choose
3126 what directory temporary files will go in, and something about what
3127 their file names will look like.  Important for multi-threaded programs
3128 is that @code{tempnam} is reentrant, while @code{tmpnam} is not since it
3129 returns a pointer to a static buffer.
3131 These facilities are declared in the header file @file{stdio.h}.
3132 @pindex stdio.h
3134 @comment stdio.h
3135 @comment ISO
3136 @deftypefun {FILE *} tmpfile (void)
3137 This function creates a temporary binary file for update mode, as if by
3138 calling @code{fopen} with mode @code{"wb+"}.  The file is deleted
3139 automatically when it is closed or when the program terminates.  (On
3140 some other @w{ISO C} systems the file may fail to be deleted if the program
3141 terminates abnormally).
3143 This function is reentrant.
3145 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
3146 32-bit system this function is in fact @code{tmpfile64}, i.e., the LFS
3147 interface transparently replaces the old interface.
3148 @end deftypefun
3150 @comment stdio.h
3151 @comment Unix98
3152 @deftypefun {FILE *} tmpfile64 (void)
3153 This function is similar to @code{tmpfile}, but the stream it returns a
3154 pointer to was opened using @code{tmpfile64}.  Therefore this stream can
3155 be used for files larger than @math{2^31} bytes on 32-bit machines.
3157 Please note that the return type is still @code{FILE *}.  There is no
3158 special @code{FILE} type for the LFS interface.
3160 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
3161 bits machine this function is available under the name @code{tmpfile}
3162 and so transparently replaces the old interface.
3163 @end deftypefun
3165 @comment stdio.h
3166 @comment ISO
3167 @deftypefun {char *} tmpnam (char *@var{result})
3168 This function constructs and returns a valid file name that does not
3169 refer to any existing file.  If the @var{result} argument is a null
3170 pointer, the return value is a pointer to an internal static string,
3171 which might be modified by subsequent calls and therefore makes this
3172 function non-reentrant.  Otherwise, the @var{result} argument should be
3173 a pointer to an array of at least @code{L_tmpnam} characters, and the
3174 result is written into that array.
3176 It is possible for @code{tmpnam} to fail if you call it too many times
3177 without removing previously-created files.  This is because the limited
3178 length of the temporary file names gives room for only a finite number
3179 of different names.  If @code{tmpnam} fails it returns a null pointer.
3181 @strong{Warning:} Between the time the pathname is constructed and the
3182 file is created another process might have created a file with the same
3183 name using @code{tmpnam}, leading to a possible security hole.  The
3184 implementation generates names which can hardly be predicted, but when
3185 opening the file you should use the @code{O_EXCL} flag.  Using
3186 @code{tmpfile} or @code{mkstemp} is a safe way to avoid this problem.
3187 @end deftypefun
3189 @comment stdio.h
3190 @comment GNU
3191 @deftypefun {char *} tmpnam_r (char *@var{result})
3192 This function is nearly identical to the @code{tmpnam} function, except
3193 that if @var{result} is a null pointer it returns a null pointer.
3195 This guarantees reentrancy because the non-reentrant situation of
3196 @code{tmpnam} cannot happen here.
3198 @strong{Warning}: This function has the same security problems as
3199 @code{tmpnam}.
3200 @end deftypefun
3202 @comment stdio.h
3203 @comment ISO
3204 @deftypevr Macro int L_tmpnam
3205 The value of this macro is an integer constant expression that
3206 represents the minimum size of a string large enough to hold a file name
3207 generated by the @code{tmpnam} function.
3208 @end deftypevr
3210 @comment stdio.h
3211 @comment ISO
3212 @deftypevr Macro int TMP_MAX
3213 The macro @code{TMP_MAX} is a lower bound for how many temporary names
3214 you can create with @code{tmpnam}.  You can rely on being able to call
3215 @code{tmpnam} at least this many times before it might fail saying you
3216 have made too many temporary file names.
3218 With @theglibc{}, you can create a very large number of temporary
3219 file names.  If you actually created the files, you would probably run
3220 out of disk space before you ran out of names.  Some other systems have
3221 a fixed, small limit on the number of temporary files.  The limit is
3222 never less than @code{25}.
3223 @end deftypevr
3225 @comment stdio.h
3226 @comment SVID
3227 @deftypefun {char *} tempnam (const char *@var{dir}, const char *@var{prefix})
3228 This function generates a unique temporary file name.  If @var{prefix}
3229 is not a null pointer, up to five characters of this string are used as
3230 a prefix for the file name.  The return value is a string newly
3231 allocated with @code{malloc}, so you should release its storage with
3232 @code{free} when it is no longer needed.
3234 Because the string is dynamically allocated this function is reentrant.
3236 The directory prefix for the temporary file name is determined by
3237 testing each of the following in sequence.  The directory must exist and
3238 be writable.
3240 @itemize @bullet
3241 @item
3242 The environment variable @code{TMPDIR}, if it is defined.  For security
3243 reasons this only happens if the program is not SUID or SGID enabled.
3245 @item
3246 The @var{dir} argument, if it is not a null pointer.
3248 @item
3249 The value of the @code{P_tmpdir} macro.
3251 @item
3252 The directory @file{/tmp}.
3253 @end itemize
3255 This function is defined for SVID compatibility.
3257 @strong{Warning:} Between the time the pathname is constructed and the
3258 file is created another process might have created a file with the same
3259 name using @code{tempnam}, leading to a possible security hole.  The
3260 implementation generates names which can hardly be predicted, but when
3261 opening the file you should use the @code{O_EXCL} flag.  Using
3262 @code{tmpfile} or @code{mkstemp} is a safe way to avoid this problem.
3263 @end deftypefun
3264 @cindex TMPDIR environment variable
3266 @comment stdio.h
3267 @comment SVID
3268 @c !!! are we putting SVID/GNU/POSIX.1/BSD in here or not??
3269 @deftypevr {SVID Macro} {char *} P_tmpdir
3270 This macro is the name of the default directory for temporary files.
3271 @end deftypevr
3273 Older Unix systems did not have the functions just described.  Instead
3274 they used @code{mktemp} and @code{mkstemp}.  Both of these functions
3275 work by modifying a file name template string you pass.  The last six
3276 characters of this string must be @samp{XXXXXX}.  These six @samp{X}s
3277 are replaced with six characters which make the whole string a unique
3278 file name.  Usually the template string is something like
3279 @samp{/tmp/@var{prefix}XXXXXX}, and each program uses a unique @var{prefix}.
3281 @strong{NB:} Because @code{mktemp} and @code{mkstemp} modify the
3282 template string, you @emph{must not} pass string constants to them.
3283 String constants are normally in read-only storage, so your program
3284 would crash when @code{mktemp} or @code{mkstemp} tried to modify the
3285 string.  These functions are declared in the header file @file{stdlib.h}.
3286 @pindex stdlib.h
3288 @comment stdlib.h
3289 @comment Unix
3290 @deftypefun {char *} mktemp (char *@var{template})
3291 The @code{mktemp} function generates a unique file name by modifying
3292 @var{template} as described above.  If successful, it returns
3293 @var{template} as modified.  If @code{mktemp} cannot find a unique file
3294 name, it makes @var{template} an empty string and returns that.  If
3295 @var{template} does not end with @samp{XXXXXX}, @code{mktemp} returns a
3296 null pointer.
3298 @strong{Warning:} Between the time the pathname is constructed and the
3299 file is created another process might have created a file with the same
3300 name using @code{mktemp}, leading to a possible security hole.  The
3301 implementation generates names which can hardly be predicted, but when
3302 opening the file you should use the @code{O_EXCL} flag.  Using
3303 @code{mkstemp} is a safe way to avoid this problem.
3304 @end deftypefun
3306 @comment stdlib.h
3307 @comment BSD
3308 @deftypefun int mkstemp (char *@var{template})
3309 The @code{mkstemp} function generates a unique file name just as
3310 @code{mktemp} does, but it also opens the file for you with @code{open}
3311 (@pxref{Opening and Closing Files}).  If successful, it modifies
3312 @var{template} in place and returns a file descriptor for that file open
3313 for reading and writing.  If @code{mkstemp} cannot create a
3314 uniquely-named file, it returns @code{-1}.  If @var{template} does not
3315 end with @samp{XXXXXX}, @code{mkstemp} returns @code{-1} and does not
3316 modify @var{template}.
3318 The file is opened using mode @code{0600}.  If the file is meant to be
3319 used by other users this mode must be changed explicitly.
3320 @end deftypefun
3322 Unlike @code{mktemp}, @code{mkstemp} is actually guaranteed to create a
3323 unique file that cannot possibly clash with any other program trying to
3324 create a temporary file.  This is because it works by calling
3325 @code{open} with the @code{O_EXCL} flag, which says you want to create a
3326 new file and get an error if the file already exists.
3328 @comment stdlib.h
3329 @comment BSD
3330 @deftypefun {char *} mkdtemp (char *@var{template})
3331 The @code{mkdtemp} function creates a directory with a unique name.  If
3332 it succeeds, it overwrites @var{template} with the name of the
3333 directory, and returns @var{template}.  As with @code{mktemp} and
3334 @code{mkstemp}, @var{template} should be a string ending with
3335 @samp{XXXXXX}.
3337 If @code{mkdtemp} cannot create an uniquely named directory, it returns
3338 @code{NULL} and sets @var{errno} appropriately.  If @var{template} does
3339 not end with @samp{XXXXXX}, @code{mkdtemp} returns @code{NULL} and does
3340 not modify @var{template}.  @var{errno} will be set to @code{EINVAL} in
3341 this case.
3343 The directory is created using mode @code{0700}.
3344 @end deftypefun
3346 The directory created by @code{mkdtemp} cannot clash with temporary
3347 files or directories created by other users.  This is because directory
3348 creation always works like @code{open} with @code{O_EXCL}.
3349 @xref{Creating Directories}.
3351 The @code{mkdtemp} function comes from OpenBSD.