As a minor cleanup remove the (r)index defines from include/string.h as
[glibc.git] / manual / filesys.texi
blobedc7c64d22169bfb9f104321b141a6b4925ce740
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 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
62 @c If buffer is NULL, this function calls malloc and realloc, and, in
63 @c case of error, free.  Linux offers a getcwd syscall that we use on
64 @c GNU/Linux systems, but it may fail if the pathname is too long.  As a
65 @c fallback, and on other systems, the generic implementation opens each
66 @c parent directory with opendir, which allocates memory for the
67 @c directory stream with malloc.  If a fstatat64 syscall is not
68 @c available, very deep directory trees may also have to malloc to build
69 @c longer sequences of ../../../... than those supported by a global
70 @c const read-only string.
72 @c linux/__getcwd
73 @c  posix/__getcwd
74 @c   malloc/realloc/free if buffer is NULL, or if dir is too deep
75 @c   lstat64 -> see its own entry
76 @c   fstatat64
77 @c     direct syscall if possible, alloca+snprintf+*stat64 otherwise
78 @c   openat64_not_cancel_3, close_not_cancel_no_status
79 @c   __fdopendir, __opendir, __readdir, rewinddir
80 The @code{getcwd} function returns an absolute file name representing
81 the current working directory, storing it in the character array
82 @var{buffer} that you provide.  The @var{size} argument is how you tell
83 the system the allocation size of @var{buffer}.
85 The @glibcadj{} version of this function also permits you to specify a
86 null pointer for the @var{buffer} argument.  Then @code{getcwd}
87 allocates a buffer automatically, as with @code{malloc}
88 (@pxref{Unconstrained Allocation}).  If the @var{size} is greater than
89 zero, then the buffer is that large; otherwise, the buffer is as large
90 as necessary to hold the result.
92 The return value is @var{buffer} on success and a null pointer on failure.
93 The following @code{errno} error conditions are defined for this function:
95 @table @code
96 @item EINVAL
97 The @var{size} argument is zero and @var{buffer} is not a null pointer.
99 @item ERANGE
100 The @var{size} argument is less than the length of the working directory
101 name.  You need to allocate a bigger array and try again.
103 @item EACCES
104 Permission to read or search a component of the file name was denied.
105 @end table
106 @end deftypefun
108 You could implement the behavior of GNU's @w{@code{getcwd (NULL, 0)}}
109 using only the standard behavior of @code{getcwd}:
111 @smallexample
112 char *
113 gnu_getcwd ()
115   size_t size = 100;
117   while (1)
118     @{
119       char *buffer = (char *) xmalloc (size);
120       if (getcwd (buffer, size) == buffer)
121         return buffer;
122       free (buffer);
123       if (errno != ERANGE)
124         return 0;
125       size *= 2;
126     @}
128 @end smallexample
130 @noindent
131 @xref{Malloc Examples}, for information about @code{xmalloc}, which is
132 not a library function but is a customary name used in most GNU
133 software.
135 @comment unistd.h
136 @comment BSD
137 @deftypefn {Deprecated Function} {char *} getwd (char *@var{buffer})
138 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @ascuintl{}}@acunsafe{@acsmem{} @acsfd{}}}
139 @c Besides the getcwd safety issues, it calls strerror_r on error, which
140 @c brings in all of the i18n issues.
141 This is similar to @code{getcwd}, but has no way to specify the size of
142 the buffer.  @Theglibc{} provides @code{getwd} only
143 for backwards compatibility with BSD.
145 The @var{buffer} argument should be a pointer to an array at least
146 @code{PATH_MAX} bytes long (@pxref{Limits for Files}).  On @gnuhurdsystems{}
147 there is no limit to the size of a file name, so this is not
148 necessarily enough space to contain the directory name.  That is why
149 this function is deprecated.
150 @end deftypefn
152 @comment unistd.h
153 @comment GNU
154 @deftypefun {char *} get_current_dir_name (void)
155 @safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
156 @c Besides getcwd, which this function calls as a fallback, it calls
157 @c getenv, with the potential thread-safety issues that brings about.
158 @vindex PWD
159 This @code{get_current_dir_name} function is basically equivalent to
160 @w{@code{getcwd (NULL, 0)}}.  The only difference is that the value of
161 the @code{PWD} variable is returned if this value is correct.  This is a
162 subtle difference which is visible if the path described by the
163 @code{PWD} value is using one or more symbol links in which case the
164 value returned by @code{getcwd} can resolve the symbol links and
165 therefore yield a different result.
167 This function is a GNU extension.
168 @end deftypefun
170 @comment unistd.h
171 @comment POSIX.1
172 @deftypefun int chdir (const char *@var{filename})
173 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
174 This function is used to set the process's working directory to
175 @var{filename}.
177 The normal, successful return value from @code{chdir} is @code{0}.  A
178 value of @code{-1} is returned to indicate an error.  The @code{errno}
179 error conditions defined for this function are the usual file name
180 syntax errors (@pxref{File Name Errors}), plus @code{ENOTDIR} if the
181 file @var{filename} is not a directory.
182 @end deftypefun
184 @comment unistd.h
185 @comment XPG
186 @deftypefun int fchdir (int @var{filedes})
187 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
188 This function is used to set the process's working directory to
189 directory associated with the file descriptor @var{filedes}.
191 The normal, successful return value from @code{fchdir} is @code{0}.  A
192 value of @code{-1} is returned to indicate an error.  The following
193 @code{errno} error conditions are defined for this function:
195 @table @code
196 @item EACCES
197 Read permission is denied for the directory named by @code{dirname}.
199 @item EBADF
200 The @var{filedes} argument is not a valid file descriptor.
202 @item ENOTDIR
203 The file descriptor @var{filedes} is not associated with a directory.
205 @item EINTR
206 The function call was interrupt by a signal.
208 @item EIO
209 An I/O error occurred.
210 @end table
211 @end deftypefun
214 @node Accessing Directories
215 @section Accessing Directories
216 @cindex accessing directories
217 @cindex reading from a directory
218 @cindex directories, accessing
220 The facilities described in this section let you read the contents of a
221 directory file.  This is useful if you want your program to list all the
222 files in a directory, perhaps as part of a menu.
224 @cindex directory stream
225 The @code{opendir} function opens a @dfn{directory stream} whose
226 elements are directory entries.  Alternatively @code{fdopendir} can be
227 used which can have advantages if the program needs to have more
228 control over the way the directory is opened for reading.  This
229 allows, for instance, to pass the @code{O_NOATIME} flag to
230 @code{open}.
232 You use the @code{readdir} function on the directory stream to
233 retrieve these entries, represented as @w{@code{struct dirent}}
234 objects.  The name of the file for each entry is stored in the
235 @code{d_name} member of this structure.  There are obvious parallels
236 here to the stream facilities for ordinary files, described in
237 @ref{I/O on Streams}.
239 @menu
240 * Directory Entries::           Format of one directory entry.
241 * Opening a Directory::         How to open a directory stream.
242 * Reading/Closing Directory::   How to read directory entries from the stream.
243 * Simple Directory Lister::     A very simple directory listing program.
244 * Random Access Directory::     Rereading part of the directory
245                                  already read with the same stream.
246 * Scanning Directory Content::  Get entries for user selected subset of
247                                  contents in given directory.
248 * Simple Directory Lister Mark II::  Revised version of the program.
249 @end menu
251 @node Directory Entries
252 @subsection Format of a Directory Entry
254 @pindex dirent.h
255 This section describes what you find in a single directory entry, as you
256 might obtain it from a directory stream.  All the symbols are declared
257 in the header file @file{dirent.h}.
259 @comment dirent.h
260 @comment POSIX.1
261 @deftp {Data Type} {struct dirent}
262 This is a structure type used to return information about directory
263 entries.  It contains the following fields:
265 @table @code
266 @item char d_name[]
267 This is the null-terminated file name component.  This is the only
268 field you can count on in all POSIX systems.
270 @item ino_t d_fileno
271 This is the file serial number.  For BSD compatibility, you can also
272 refer to this member as @code{d_ino}.  On @gnulinuxhurdsystems{} and most POSIX
273 systems, for most files this the same as the @code{st_ino} member that
274 @code{stat} will return for the file.  @xref{File Attributes}.
276 @item unsigned char d_namlen
277 This is the length of the file name, not including the terminating
278 null character.  Its type is @code{unsigned char} because that is the
279 integer type of the appropriate size.  This member is a BSD extension.
280 The symbol @code{_DIRENT_HAVE_D_NAMLEN} is defined if this member is
281 available.
283 @item unsigned char d_type
284 This is the type of the file, possibly unknown.  The following constants
285 are defined for its value:
287 @vtable @code
288 @item DT_UNKNOWN
289 The type is unknown.  Only some filesystems have full support to
290 return the type of the file, others might always return this value.
292 @item DT_REG
293 A regular file.
295 @item DT_DIR
296 A directory.
298 @item DT_FIFO
299 A named pipe, or FIFO.  @xref{FIFO Special Files}.
301 @item DT_SOCK
302 A local-domain socket.  @c !!! @xref{Local Domain}.
304 @item DT_CHR
305 A character device.
307 @item DT_BLK
308 A block device.
310 @item DT_LNK
311 A symbolic link.
312 @end vtable
314 This member is a BSD extension.  The symbol @code{_DIRENT_HAVE_D_TYPE}
315 is defined if this member is available.  On systems where it is used, it
316 corresponds to the file type bits in the @code{st_mode} member of
317 @code{struct stat}.  If the value cannot be determined the member
318 value is DT_UNKNOWN.  These two macros convert between @code{d_type}
319 values and @code{st_mode} values:
321 @comment dirent.h
322 @comment BSD
323 @deftypefun int IFTODT (mode_t @var{mode})
324 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
325 This returns the @code{d_type} value corresponding to @var{mode}.
326 @end deftypefun
328 @comment dirent.h
329 @comment BSD
330 @deftypefun mode_t DTTOIF (int @var{dtype})
331 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
332 This returns the @code{st_mode} value corresponding to @var{dtype}.
333 @end deftypefun
334 @end table
336 This structure may contain additional members in the future.  Their
337 availability is always announced in the compilation environment by a
338 macro named @code{_DIRENT_HAVE_D_@var{xxx}} where @var{xxx} is replaced
339 by the name of the new member.  For instance, the member @code{d_reclen}
340 available on some systems is announced through the macro
341 @code{_DIRENT_HAVE_D_RECLEN}.
343 When a file has multiple names, each name has its own directory entry.
344 The only way you can tell that the directory entries belong to a
345 single file is that they have the same value for the @code{d_fileno}
346 field.
348 File attributes such as size, modification times etc., are part of the
349 file itself, not of any particular directory entry.  @xref{File
350 Attributes}.
351 @end deftp
353 @node Opening a Directory
354 @subsection Opening a Directory Stream
356 @pindex dirent.h
357 This section describes how to open a directory stream.  All the symbols
358 are declared in the header file @file{dirent.h}.
360 @comment dirent.h
361 @comment POSIX.1
362 @deftp {Data Type} DIR
363 The @code{DIR} data type represents a directory stream.
364 @end deftp
366 You shouldn't ever allocate objects of the @code{struct dirent} or
367 @code{DIR} data types, since the directory access functions do that for
368 you.  Instead, you refer to these objects using the pointers returned by
369 the following functions.
371 @comment dirent.h
372 @comment POSIX.1
373 @deftypefun {DIR *} opendir (const char *@var{dirname})
374 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
375 @c Besides the safe syscall, we have to allocate the DIR object with
376 @c __alloc_dir, that calls malloc.
377 The @code{opendir} function opens and returns a directory stream for
378 reading the directory whose file name is @var{dirname}.  The stream has
379 type @code{DIR *}.
381 If unsuccessful, @code{opendir} returns a null pointer.  In addition to
382 the usual file name errors (@pxref{File Name Errors}), the
383 following @code{errno} error conditions are defined for this function:
385 @table @code
386 @item EACCES
387 Read permission is denied for the directory named by @code{dirname}.
389 @item EMFILE
390 The process has too many files open.
392 @item ENFILE
393 The entire system, or perhaps the file system which contains the
394 directory, cannot support any additional open files at the moment.
395 (This problem cannot happen on @gnuhurdsystems{}.)
397 @item ENOMEM
398 Not enough memory available.
399 @end table
401 The @code{DIR} type is typically implemented using a file descriptor,
402 and the @code{opendir} function in terms of the @code{open} function.
403 @xref{Low-Level I/O}.  Directory streams and the underlying
404 file descriptors are closed on @code{exec} (@pxref{Executing a File}).
405 @end deftypefun
407 The directory which is opened for reading by @code{opendir} is
408 identified by the name.  In some situations this is not sufficient.
409 Or the way @code{opendir} implicitly creates a file descriptor for the
410 directory is not the way a program might want it.  In these cases an
411 alternative interface can be used.
413 @comment dirent.h
414 @comment GNU
415 @deftypefun {DIR *} fdopendir (int @var{fd})
416 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
417 @c The DIR object is allocated with __alloc_dir, that calls malloc.
418 The @code{fdopendir} function works just like @code{opendir} but
419 instead of taking a file name and opening a file descriptor for the
420 directory the caller is required to provide a file descriptor.  This
421 file descriptor is then used in subsequent uses of the returned
422 directory stream object.
424 The caller must make sure the file descriptor is associated with a
425 directory and it allows reading.
427 If the @code{fdopendir} call returns successfully the file descriptor
428 is now under the control of the system.  It can be used in the same
429 way the descriptor implicitly created by @code{opendir} can be used
430 but the program must not close the descriptor.
432 In case the function is unsuccessful it returns a null pointer and the
433 file descriptor remains to be usable by the program.  The following
434 @code{errno} error conditions are defined for this function:
436 @table @code
437 @item EBADF
438 The file descriptor is not valid.
440 @item ENOTDIR
441 The file descriptor is not associated with a directory.
443 @item EINVAL
444 The descriptor does not allow reading the directory content.
446 @item ENOMEM
447 Not enough memory available.
448 @end table
449 @end deftypefun
451 In some situations it can be desirable to get hold of the file
452 descriptor which is created by the @code{opendir} call.  For instance,
453 to switch the current working directory to the directory just read the
454 @code{fchdir} function could be used.  Historically the @code{DIR} type
455 was exposed and programs could access the fields.  This does not happen
456 in @theglibc{}.  Instead a separate function is provided to allow
457 access.
459 @comment dirent.h
460 @comment GNU
461 @deftypefun int dirfd (DIR *@var{dirstream})
462 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
463 The function @code{dirfd} returns the file descriptor associated with
464 the directory stream @var{dirstream}.  This descriptor can be used until
465 the directory is closed with @code{closedir}.  If the directory stream
466 implementation is not using file descriptors the return value is
467 @code{-1}.
468 @end deftypefun
470 @node Reading/Closing Directory
471 @subsection Reading and Closing a Directory Stream
473 @pindex dirent.h
474 This section describes how to read directory entries from a directory
475 stream, and how to close the stream when you are done with it.  All the
476 symbols are declared in the header file @file{dirent.h}.
478 @comment dirent.h
479 @comment POSIX.1
480 @deftypefun {struct dirent *} readdir (DIR *@var{dirstream})
481 @safety{@prelim{}@mtunsafe{@mtasurace{:dirstream}}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
482 @c This function holds dirstream's non-recursive lock, which brings
483 @c about the usual issues with locks and async signals and cancellation,
484 @c but the lock taking is not enough to make the returned value safe to
485 @c use, since it points to a stream's internal buffer that can be
486 @c overwritten by subsequent calls or even released by closedir.
487 This function reads the next entry from the directory.  It normally
488 returns a pointer to a structure containing information about the
489 file.  This structure is associated with the @var{dirstream} handle
490 and can be rewritten by a subsequent call.
492 @strong{Portability Note:} On some systems @code{readdir} may not
493 return entries for @file{.} and @file{..}, even though these are always
494 valid file names in any directory.  @xref{File Name Resolution}.
496 If there are no more entries in the directory or an error is detected,
497 @code{readdir} returns a null pointer.  The following @code{errno} error
498 conditions are defined for this function:
500 @table @code
501 @item EBADF
502 The @var{dirstream} argument is not valid.
503 @end table
505 To distinguish between an end-of-directory condition or an error, you
506 must set @code{errno} to zero before calling @code{readdir}.  To avoid
507 entering an infinite loop, you should stop reading from the directory
508 after the first error.
510 In POSIX.1-2008, @code{readdir} is not thread-safe.  In @theglibc{}
511 implementation, it is safe to call @code{readdir} concurrently on
512 different @var{dirstream}s, but multiple threads accessing the same
513 @var{dirstream} result in undefined behavior.  @code{readdir_r} is a
514 fully thread-safe alternative, but suffers from poor portability (see
515 below).  It is recommended that you use @code{readdir}, with external
516 locking if multiple threads access the same @var{dirstream}.
517 @end deftypefun
519 @comment dirent.h
520 @comment GNU
521 @deftypefun int readdir_r (DIR *@var{dirstream}, struct dirent *@var{entry}, struct dirent **@var{result})
522 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
523 This function is a version of @code{readdir} which performs internal
524 locking.  Like @code{readdir} it returns the next entry from the
525 directory.  To prevent conflicts between simultaneously running
526 threads the result is stored inside the @var{entry} object.
528 @strong{Portability Note:} @code{readdir_r} is deprecated.  It is
529 recommended to use @code{readdir} instead of @code{readdir_r} for the
530 following reasons:
532 @itemize @bullet
533 @item
534 On systems which do not define @code{NAME_MAX}, it may not be possible
535 to use @code{readdir_r} safely because the caller does not specify the
536 length of the buffer for the directory entry.
538 @item
539 On some systems, @code{readdir_r} cannot read directory entries with
540 very long names.  If such a name is encountered, @theglibc{}
541 implementation of @code{readdir_r} returns with an error code of
542 @code{ENAMETOOLONG} after the final directory entry has been read.  On
543 other systems, @code{readdir_r} may return successfully, but the
544 @code{d_name} member may not be NUL-terminated or may be truncated.
546 @item
547 POSIX-1.2008 does not guarantee that @code{readdir} is thread-safe,
548 even when access to the same @var{dirstream} is serialized.  But in
549 current implementations (including @theglibc{}), it is safe to call
550 @code{readdir} concurrently on different @var{dirstream}s, so there is
551 no need to use @code{readdir_r} in most multi-threaded programs.  In
552 the rare case that multiple threads need to read from the same
553 @var{dirstream}, it is still better to use @code{readdir} and external
554 synchronization.
556 @item
557 It is expected that future versions of POSIX will obsolete
558 @code{readdir_r} and mandate the level of thread safety for
559 @code{readdir} which is provided by @theglibc{} and other
560 implementations today.
561 @end itemize
563 Normally @code{readdir_r} returns zero and sets @code{*@var{result}}
564 to @var{entry}.  If there are no more entries in the directory or an
565 error is detected, @code{readdir_r} sets @code{*@var{result}} to a
566 null pointer and returns a nonzero error code, also stored in
567 @code{errno}, as described for @code{readdir}.
569 It is also important to look at the definition of the @code{struct
570 dirent} type.  Simply passing a pointer to an object of this type for
571 the second parameter of @code{readdir_r} might not be enough.  Some
572 systems don't define the @code{d_name} element sufficiently long.  In
573 this case the user has to provide additional space.  There must be room
574 for at least @code{NAME_MAX + 1} characters in the @code{d_name} array.
575 Code to call @code{readdir_r} could look like this:
577 @smallexample
578   union
579   @{
580     struct dirent d;
581     char b[offsetof (struct dirent, d_name) + NAME_MAX + 1];
582   @} u;
584   if (readdir_r (dir, &u.d, &res) == 0)
585     @dots{}
586 @end smallexample
587 @end deftypefun
589 To support large filesystems on 32-bit machines there are LFS variants
590 of the last two functions.
592 @comment dirent.h
593 @comment LFS
594 @deftypefun {struct dirent64 *} readdir64 (DIR *@var{dirstream})
595 @safety{@prelim{}@mtunsafe{@mtasurace{:dirstream}}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
596 The @code{readdir64} function is just like the @code{readdir} function
597 except that it returns a pointer to a record of type @code{struct
598 dirent64}.  Some of the members of this data type (notably @code{d_ino})
599 might have a different size to allow large filesystems.
601 In all other aspects this function is equivalent to @code{readdir}.
602 @end deftypefun
604 @comment dirent.h
605 @comment LFS
606 @deftypefun int readdir64_r (DIR *@var{dirstream}, struct dirent64 *@var{entry}, struct dirent64 **@var{result})
607 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
608 The deprecated @code{readdir64_r} function is equivalent to the
609 @code{readdir_r} function except that it takes parameters of base type
610 @code{struct dirent64} instead of @code{struct dirent} in the second and
611 third position.  The same precautions mentioned in the documentation of
612 @code{readdir_r} also apply here.
613 @end deftypefun
615 @comment dirent.h
616 @comment POSIX.1
617 @deftypefun int closedir (DIR *@var{dirstream})
618 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{/hurd}}@acunsafe{@acsmem{} @acsfd{} @aculock{/hurd}}}
619 @c No synchronization in the posix implementation, only in the hurd
620 @c one.  This is regarded as safe because it is undefined behavior if
621 @c other threads could still be using the dir stream while it's closed.
622 This function closes the directory stream @var{dirstream}.  It returns
623 @code{0} on success and @code{-1} on failure.
625 The following @code{errno} error conditions are defined for this
626 function:
628 @table @code
629 @item EBADF
630 The @var{dirstream} argument is not valid.
631 @end table
632 @end deftypefun
634 @node Simple Directory Lister
635 @subsection Simple Program to List a Directory
637 Here's a simple program that prints the names of the files in
638 the current working directory:
640 @smallexample
641 @include dir.c.texi
642 @end smallexample
644 The order in which files appear in a directory tends to be fairly
645 random.  A more useful program would sort the entries (perhaps by
646 alphabetizing them) before printing them; see
647 @ref{Scanning Directory Content}, and @ref{Array Sort Function}.
650 @node Random Access Directory
651 @subsection Random Access in a Directory Stream
653 @pindex dirent.h
654 This section describes how to reread parts of a directory that you have
655 already read from an open directory stream.  All the symbols are
656 declared in the header file @file{dirent.h}.
658 @comment dirent.h
659 @comment POSIX.1
660 @deftypefun void rewinddir (DIR *@var{dirstream})
661 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
662 The @code{rewinddir} function is used to reinitialize the directory
663 stream @var{dirstream}, so that if you call @code{readdir} it
664 returns information about the first entry in the directory again.  This
665 function also notices if files have been added or removed to the
666 directory since it was opened with @code{opendir}.  (Entries for these
667 files might or might not be returned by @code{readdir} if they were
668 added or removed since you last called @code{opendir} or
669 @code{rewinddir}.)
670 @end deftypefun
672 @comment dirent.h
673 @comment BSD
674 @deftypefun {long int} telldir (DIR *@var{dirstream})
675 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{/bsd} @asulock{/bsd}}@acunsafe{@acsmem{/bsd} @aculock{/bsd}}}
676 @c The implementation is safe on most platforms, but on BSD it uses
677 @c cookies, buckets and records, and the global array of pointers to
678 @c dynamically allocated records is guarded by a non-recursive lock.
679 The @code{telldir} function returns the file position of the directory
680 stream @var{dirstream}.  You can use this value with @code{seekdir} to
681 restore the directory stream to that position.
682 @end deftypefun
684 @comment dirent.h
685 @comment BSD
686 @deftypefun void seekdir (DIR *@var{dirstream}, long int @var{pos})
687 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{/bsd} @asulock{/bsd}}@acunsafe{@acsmem{/bsd} @aculock{/bsd}}}
688 @c The implementation is safe on most platforms, but on BSD it uses
689 @c cookies, buckets and records, and the global array of pointers to
690 @c dynamically allocated records is guarded by a non-recursive lock.
691 The @code{seekdir} function sets the file position of the directory
692 stream @var{dirstream} to @var{pos}.  The value @var{pos} must be the
693 result of a previous call to @code{telldir} on this particular stream;
694 closing and reopening the directory can invalidate values returned by
695 @code{telldir}.
696 @end deftypefun
699 @node Scanning Directory Content
700 @subsection Scanning the Content of a Directory
702 A higher-level interface to the directory handling functions is the
703 @code{scandir} function.  With its help one can select a subset of the
704 entries in a directory, possibly sort them and get a list of names as
705 the result.
707 @comment dirent.h
708 @comment BSD/SVID
709 @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 **))
710 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
711 @c The scandir function calls __opendirat, __readdir, and __closedir to
712 @c go over the named dir; malloc and realloc to allocate the namelist
713 @c and copies of each selected dirent, besides the selector, if given,
714 @c and qsort and the cmp functions if the latter is given.  In spite of
715 @c the cleanup handler that releases memory and the file descriptor in
716 @c case of synchronous cancellation, an asynchronous cancellation may
717 @c still leak memory and a file descriptor.  Although readdir is unsafe
718 @c in general, the use of an internal dir stream for sequential scanning
719 @c of the directory with copying of dirents before subsequent calls
720 @c makes the use safe, and the fact that the dir stream is private to
721 @c each scandir call does away with the lock issues in readdir and
722 @c closedir.
724 The @code{scandir} function scans the contents of the directory selected
725 by @var{dir}.  The result in *@var{namelist} is an array of pointers to
726 structures of type @code{struct dirent} which describe all selected
727 directory entries and which is allocated using @code{malloc}.  Instead
728 of always getting all directory entries returned, the user supplied
729 function @var{selector} can be used to decide which entries are in the
730 result.  Only the entries for which @var{selector} returns a non-zero
731 value are selected.
733 Finally the entries in *@var{namelist} are sorted using the
734 user-supplied function @var{cmp}.  The arguments passed to the @var{cmp}
735 function are of type @code{struct dirent **}, therefore one cannot
736 directly use the @code{strcmp} or @code{strcoll} functions; instead see
737 the functions @code{alphasort} and @code{versionsort} below.
739 The return value of the function is the number of entries placed in
740 *@var{namelist}.  If it is @code{-1} an error occurred (either the
741 directory could not be opened for reading or the malloc call failed) and
742 the global variable @code{errno} contains more information on the error.
743 @end deftypefun
745 As described above, the fourth argument to the @code{scandir} function
746 must be a pointer to a sorting function.  For the convenience of the
747 programmer @theglibc{} contains implementations of functions which
748 are very helpful for this purpose.
750 @comment dirent.h
751 @comment BSD/SVID
752 @deftypefun int alphasort (const struct dirent **@var{a}, const struct dirent **@var{b})
753 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
754 @c Calls strcoll.
755 The @code{alphasort} function behaves like the @code{strcoll} function
756 (@pxref{String/Array Comparison}).  The difference is that the arguments
757 are not string pointers but instead they are of type
758 @code{struct dirent **}.
760 The return value of @code{alphasort} is less than, equal to, or greater
761 than zero depending on the order of the two entries @var{a} and @var{b}.
762 @end deftypefun
764 @comment dirent.h
765 @comment GNU
766 @deftypefun int versionsort (const struct dirent **@var{a}, const struct dirent **@var{b})
767 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
768 @c Calls strverscmp, which will accesses the locale object multiple
769 @c times.
770 The @code{versionsort} function is like @code{alphasort} except that it
771 uses the @code{strverscmp} function internally.
772 @end deftypefun
774 If the filesystem supports large files we cannot use the @code{scandir}
775 anymore since the @code{dirent} structure might not able to contain all
776 the information.  The LFS provides the new type @w{@code{struct
777 dirent64}}.  To use this we need a new function.
779 @comment dirent.h
780 @comment GNU
781 @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 **))
782 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
783 @c See scandir.
784 The @code{scandir64} function works like the @code{scandir} function
785 except that the directory entries it returns are described by elements
786 of type @w{@code{struct dirent64}}.  The function pointed to by
787 @var{selector} is again used to select the desired entries, except that
788 @var{selector} now must point to a function which takes a
789 @w{@code{struct dirent64 *}} parameter.
791 Similarly the @var{cmp} function should expect its two arguments to be
792 of type @code{struct dirent64 **}.
793 @end deftypefun
795 As @var{cmp} is now a function of a different type, the functions
796 @code{alphasort} and @code{versionsort} cannot be supplied for that
797 argument.  Instead we provide the two replacement functions below.
799 @comment dirent.h
800 @comment GNU
801 @deftypefun int alphasort64 (const struct dirent64 **@var{a}, const struct dirent **@var{b})
802 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
803 @c See alphasort.
804 The @code{alphasort64} function behaves like the @code{strcoll} function
805 (@pxref{String/Array Comparison}).  The difference is that the arguments
806 are not string pointers but instead they are of type
807 @code{struct dirent64 **}.
809 Return value of @code{alphasort64} is less than, equal to, or greater
810 than zero depending on the order of the two entries @var{a} and @var{b}.
811 @end deftypefun
813 @comment dirent.h
814 @comment GNU
815 @deftypefun int versionsort64 (const struct dirent64 **@var{a}, const struct dirent64 **@var{b})
816 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
817 @c See versionsort.
818 The @code{versionsort64} function is like @code{alphasort64}, excepted that it
819 uses the @code{strverscmp} function internally.
820 @end deftypefun
822 It is important not to mix the use of @code{scandir} and the 64-bit
823 comparison functions or vice versa.  There are systems on which this
824 works but on others it will fail miserably.
826 @node Simple Directory Lister Mark II
827 @subsection Simple Program to List a Directory, Mark II
829 Here is a revised version of the directory lister found above
830 (@pxref{Simple Directory Lister}).  Using the @code{scandir} function we
831 can avoid the functions which work directly with the directory contents.
832 After the call the returned entries are available for direct use.
834 @smallexample
835 @include dir2.c.texi
836 @end smallexample
838 Note the simple selector function in this example.  Since we want to see
839 all directory entries we always return @code{1}.
842 @node Working with Directory Trees
843 @section Working with Directory Trees
844 @cindex directory hierarchy
845 @cindex hierarchy, directory
846 @cindex tree, directory
848 The functions described so far for handling the files in a directory
849 have allowed you to either retrieve the information bit by bit, or to
850 process all the files as a group (see @code{scandir}).  Sometimes it is
851 useful to process whole hierarchies of directories and their contained
852 files.  The X/Open specification defines two functions to do this.  The
853 simpler form is derived from an early definition in @w{System V} systems
854 and therefore this function is available on SVID-derived systems.  The
855 prototypes and required definitions can be found in the @file{ftw.h}
856 header.
858 There are four functions in this family: @code{ftw}, @code{nftw} and
859 their 64-bit counterparts @code{ftw64} and @code{nftw64}.  These
860 functions take as one of their arguments a pointer to a callback
861 function of the appropriate type.
863 @comment ftw.h
864 @comment GNU
865 @deftp {Data Type} __ftw_func_t
867 @smallexample
868 int (*) (const char *, const struct stat *, int)
869 @end smallexample
871 The type of callback functions given to the @code{ftw} function.  The
872 first parameter points to the file name, the second parameter to an
873 object of type @code{struct stat} which is filled in for the file named
874 in the first parameter.
876 @noindent
877 The last parameter is a flag giving more information about the current
878 file.  It can have the following values:
880 @vtable @code
881 @item FTW_F
882 The item is either a normal file or a file which does not fit into one
883 of the following categories.  This could be special files, sockets etc.
884 @item FTW_D
885 The item is a directory.
886 @item FTW_NS
887 The @code{stat} call failed and so the information pointed to by the
888 second parameter is invalid.
889 @item FTW_DNR
890 The item is a directory which cannot be read.
891 @item FTW_SL
892 The item is a symbolic link.  Since symbolic links are normally followed
893 seeing this value in a @code{ftw} callback function means the referenced
894 file does not exist.  The situation for @code{nftw} is different.
896 This value is only available if the program is compiled with
897 @code{_XOPEN_EXTENDED} defined before including
898 the first header.  The original SVID systems do not have symbolic links.
899 @end vtable
901 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
902 type is in fact @code{__ftw64_func_t} since this mode changes
903 @code{struct stat} to be @code{struct stat64}.
904 @end deftp
906 For the LFS interface and for use in the function @code{ftw64}, the
907 header @file{ftw.h} defines another function type.
909 @comment ftw.h
910 @comment GNU
911 @deftp {Data Type} __ftw64_func_t
913 @smallexample
914 int (*) (const char *, const struct stat64 *, int)
915 @end smallexample
917 This type is used just like @code{__ftw_func_t} for the callback
918 function, but this time is called from @code{ftw64}.  The second
919 parameter to the function is a pointer to a variable of type
920 @code{struct stat64} which is able to represent the larger values.
921 @end deftp
923 @comment ftw.h
924 @comment GNU
925 @deftp {Data Type} __nftw_func_t
927 @smallexample
928 int (*) (const char *, const struct stat *, int, struct FTW *)
929 @end smallexample
931 The first three arguments are the same as for the @code{__ftw_func_t}
932 type.  However for the third argument some additional values are defined
933 to allow finer differentiation:
934 @vtable @code
935 @item FTW_DP
936 The current item is a directory and all subdirectories have already been
937 visited and reported.  This flag is returned instead of @code{FTW_D} if
938 the @code{FTW_DEPTH} flag is passed to @code{nftw} (see below).
939 @item FTW_SLN
940 The current item is a stale symbolic link.  The file it points to does
941 not exist.
942 @end vtable
944 The last parameter of the callback function is a pointer to a structure
945 with some extra information as described below.
947 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
948 type is in fact @code{__nftw64_func_t} since this mode changes
949 @code{struct stat} to be @code{struct stat64}.
950 @end deftp
952 For the LFS interface there is also a variant of this data type
953 available which has to be used with the @code{nftw64} function.
955 @comment ftw.h
956 @comment GNU
957 @deftp {Data Type} __nftw64_func_t
959 @smallexample
960 int (*) (const char *, const struct stat64 *, int, struct FTW *)
961 @end smallexample
963 This type is used just like @code{__nftw_func_t} for the callback
964 function, but this time is called from @code{nftw64}.  The second
965 parameter to the function is this time a pointer to a variable of type
966 @code{struct stat64} which is able to represent the larger values.
967 @end deftp
969 @comment ftw.h
970 @comment XPG4.2
971 @deftp {Data Type} {struct FTW}
972 The information contained in this structure helps in interpreting the
973 name parameter and gives some information about the current state of the
974 traversal of the directory hierarchy.
976 @table @code
977 @item int base
978 The value is the offset into the string passed in the first parameter to
979 the callback function of the beginning of the file name.  The rest of
980 the string is the path of the file.  This information is especially
981 important if the @code{FTW_CHDIR} flag was set in calling @code{nftw}
982 since then the current directory is the one the current item is found
984 @item int level
985 Whilst processing, the code tracks how many directories down it has gone
986 to find the current file.  This nesting level starts at @math{0} for
987 files in the initial directory (or is zero for the initial file if a
988 file was passed).
989 @end table
990 @end deftp
993 @comment ftw.h
994 @comment SVID
995 @deftypefun int ftw (const char *@var{filename}, __ftw_func_t @var{func}, int @var{descriptors})
996 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
997 @c see nftw for safety details
998 The @code{ftw} function calls the callback function given in the
999 parameter @var{func} for every item which is found in the directory
1000 specified by @var{filename} and all directories below.  The function
1001 follows symbolic links if necessary but does not process an item twice.
1002 If @var{filename} is not a directory then it itself is the only object
1003 returned to the callback function.
1005 The file name passed to the callback function is constructed by taking
1006 the @var{filename} parameter and appending the names of all passed
1007 directories and then the local file name.  So the callback function can
1008 use this parameter to access the file.  @code{ftw} also calls
1009 @code{stat} for the file and passes that information on to the callback
1010 function.  If this @code{stat} call is not successful the failure is
1011 indicated by setting the third argument of the callback function to
1012 @code{FTW_NS}.  Otherwise it is set according to the description given
1013 in the account of @code{__ftw_func_t} above.
1015 The callback function is expected to return @math{0} to indicate that no
1016 error occurred and that processing should continue.  If an error
1017 occurred in the callback function or it wants @code{ftw} to return
1018 immediately, the callback function can return a value other than
1019 @math{0}.  This is the only correct way to stop the function.  The
1020 program must not use @code{setjmp} or similar techniques to continue
1021 from another place.  This would leave resources allocated by the
1022 @code{ftw} function unfreed.
1024 The @var{descriptors} parameter to @code{ftw} specifies how many file
1025 descriptors it is allowed to consume.  The function runs faster the more
1026 descriptors it can use.  For each level in the directory hierarchy at
1027 most one descriptor is used, but for very deep ones any limit on open
1028 file descriptors for the process or the system may be exceeded.
1029 Moreover, file descriptor limits in a multi-threaded program apply to
1030 all the threads as a group, and therefore it is a good idea to supply a
1031 reasonable limit to the number of open descriptors.
1033 The return value of the @code{ftw} function is @math{0} if all callback
1034 function calls returned @math{0} and all actions performed by the
1035 @code{ftw} succeeded.  If a function call failed (other than calling
1036 @code{stat} on an item) the function returns @math{-1}.  If a callback
1037 function returns a value other than @math{0} this value is returned as
1038 the return value of @code{ftw}.
1040 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1041 32-bit system this function is in fact @code{ftw64}, i.e., the LFS
1042 interface transparently replaces the old interface.
1043 @end deftypefun
1045 @comment ftw.h
1046 @comment Unix98
1047 @deftypefun int ftw64 (const char *@var{filename}, __ftw64_func_t @var{func}, int @var{descriptors})
1048 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
1049 This function is similar to @code{ftw} but it can work on filesystems
1050 with large files.  File information is reported using a variable of type
1051 @code{struct stat64} which is passed by reference to the callback
1052 function.
1054 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1055 32-bit system this function is available under the name @code{ftw} and
1056 transparently replaces the old implementation.
1057 @end deftypefun
1059 @comment ftw.h
1060 @comment XPG4.2
1061 @deftypefun int nftw (const char *@var{filename}, __nftw_func_t @var{func}, int @var{descriptors}, int @var{flag})
1062 @safety{@prelim{}@mtsafe{@mtasscwd{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{} @acscwd{}}}
1063 @c ftw_startup calls alloca, malloc, free, xstat/lxstat, tdestroy, and ftw_dir
1064 @c  if FTW_CHDIR, call open, and fchdir, or chdir and getcwd
1065 @c ftw_dir calls open_dir_stream, readdir64, process_entry, closedir
1066 @c  if FTW_CHDIR, also calls fchdir
1067 @c open_dir_stream calls malloc, realloc, readdir64, free, closedir,
1068 @c  then openat64_not_cancel_3 and fdopendir or opendir, then dirfd.
1069 @c process_entry may cal realloc, fxstatat/lxstat/xstat, ftw_dir, and
1070 @c  find_object (tsearch) and add_object (tfind).
1071 @c Since each invocation of *ftw uses its own private search tree, none
1072 @c  of the search tree concurrency issues apply.
1073 The @code{nftw} function works like the @code{ftw} functions.  They call
1074 the callback function @var{func} for all items found in the directory
1075 @var{filename} and below.  At most @var{descriptors} file descriptors
1076 are consumed during the @code{nftw} call.
1078 One difference is that the callback function is of a different type.  It
1079 is of type @w{@code{struct FTW *}} and provides the callback function
1080 with the extra information described above.
1082 A second difference is that @code{nftw} takes a fourth argument, which
1083 is @math{0} or a bitwise-OR combination of any of the following values.
1085 @vtable @code
1086 @item FTW_PHYS
1087 While traversing the directory symbolic links are not followed.  Instead
1088 symbolic links are reported using the @code{FTW_SL} value for the type
1089 parameter to the callback function.  If the file referenced by a
1090 symbolic link does not exist @code{FTW_SLN} is returned instead.
1091 @item FTW_MOUNT
1092 The callback function is only called for items which are on the same
1093 mounted filesystem as the directory given by the @var{filename}
1094 parameter to @code{nftw}.
1095 @item FTW_CHDIR
1096 If this flag is given the current working directory is changed to the
1097 directory of the reported object before the callback function is called.
1098 When @code{ntfw} finally returns the current directory is restored to
1099 its original value.
1100 @item FTW_DEPTH
1101 If this option is specified then all subdirectories and files within
1102 them are processed before processing the top directory itself
1103 (depth-first processing).  This also means the type flag given to the
1104 callback function is @code{FTW_DP} and not @code{FTW_D}.
1105 @item FTW_ACTIONRETVAL
1106 If this option is specified then return values from callbacks
1107 are handled differently.  If the callback returns @code{FTW_CONTINUE},
1108 walking continues normally.  @code{FTW_STOP} means walking stops
1109 and @code{FTW_STOP} is returned to the caller.  If @code{FTW_SKIP_SUBTREE}
1110 is returned by the callback with @code{FTW_D} argument, the subtree
1111 is skipped and walking continues with next sibling of the directory.
1112 If @code{FTW_SKIP_SIBLINGS} is returned by the callback, all siblings
1113 of the current entry are skipped and walking continues in its parent.
1114 No other return values should be returned from the callbacks if
1115 this option is set.  This option is a GNU extension.
1116 @end vtable
1118 The return value is computed in the same way as for @code{ftw}.
1119 @code{nftw} returns @math{0} if no failures occurred and all callback
1120 functions returned @math{0}.  In case of internal errors, such as memory
1121 problems, the return value is @math{-1} and @var{errno} is set
1122 accordingly.  If the return value of a callback invocation was non-zero
1123 then that value is returned.
1125 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1126 32-bit system this function is in fact @code{nftw64}, i.e., the LFS
1127 interface transparently replaces the old interface.
1128 @end deftypefun
1130 @comment ftw.h
1131 @comment Unix98
1132 @deftypefun int nftw64 (const char *@var{filename}, __nftw64_func_t @var{func}, int @var{descriptors}, int @var{flag})
1133 @safety{@prelim{}@mtsafe{@mtasscwd{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{} @acscwd{}}}
1134 This function is similar to @code{nftw} but it can work on filesystems
1135 with large files.  File information is reported using a variable of type
1136 @code{struct stat64} which is passed by reference to the callback
1137 function.
1139 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1140 32-bit system this function is available under the name @code{nftw} and
1141 transparently replaces the old implementation.
1142 @end deftypefun
1145 @node Hard Links
1146 @section Hard Links
1147 @cindex hard link
1148 @cindex link, hard
1149 @cindex multiple names for one file
1150 @cindex file names, multiple
1152 In POSIX systems, one file can have many names at the same time.  All of
1153 the names are equally real, and no one of them is preferred to the
1154 others.
1156 To add a name to a file, use the @code{link} function.  (The new name is
1157 also called a @dfn{hard link} to the file.)  Creating a new link to a
1158 file does not copy the contents of the file; it simply makes a new name
1159 by which the file can be known, in addition to the file's existing name
1160 or names.
1162 One file can have names in several directories, so the organization
1163 of the file system is not a strict hierarchy or tree.
1165 In most implementations, it is not possible to have hard links to the
1166 same file in multiple file systems.  @code{link} reports an error if you
1167 try to make a hard link to the file from another file system when this
1168 cannot be done.
1170 The prototype for the @code{link} function is declared in the header
1171 file @file{unistd.h}.
1172 @pindex unistd.h
1174 @comment unistd.h
1175 @comment POSIX.1
1176 @deftypefun int link (const char *@var{oldname}, const char *@var{newname})
1177 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1178 The @code{link} function makes a new link to the existing file named by
1179 @var{oldname}, under the new name @var{newname}.
1181 This function returns a value of @code{0} if it is successful and
1182 @code{-1} on failure.  In addition to the usual file name errors
1183 (@pxref{File Name Errors}) for both @var{oldname} and @var{newname}, the
1184 following @code{errno} error conditions are defined for this function:
1186 @table @code
1187 @item EACCES
1188 You are not allowed to write to the directory in which the new link is
1189 to be written.
1190 @ignore
1191 Some implementations also require that the existing file be accessible
1192 by the caller, and use this error to report failure for that reason.
1193 @end ignore
1195 @item EEXIST
1196 There is already a file named @var{newname}.  If you want to replace
1197 this link with a new link, you must remove the old link explicitly first.
1199 @item EMLINK
1200 There are already too many links to the file named by @var{oldname}.
1201 (The maximum number of links to a file is @w{@code{LINK_MAX}}; see
1202 @ref{Limits for Files}.)
1204 @item ENOENT
1205 The file named by @var{oldname} doesn't exist.  You can't make a link to
1206 a file that doesn't exist.
1208 @item ENOSPC
1209 The directory or file system that would contain the new link is full
1210 and cannot be extended.
1212 @item EPERM
1213 On @gnulinuxhurdsystems{} and some others, you cannot make links to
1214 directories.
1215 Many systems allow only privileged users to do so.  This error
1216 is used to report the problem.
1218 @item EROFS
1219 The directory containing the new link can't be modified because it's on
1220 a read-only file system.
1222 @item EXDEV
1223 The directory specified in @var{newname} is on a different file system
1224 than the existing file.
1226 @item EIO
1227 A hardware error occurred while trying to read or write the to filesystem.
1228 @end table
1229 @end deftypefun
1231 @node Symbolic Links
1232 @section Symbolic Links
1233 @cindex soft link
1234 @cindex link, soft
1235 @cindex symbolic link
1236 @cindex link, symbolic
1238 @gnusystems{} support @dfn{soft links} or @dfn{symbolic links}.  This
1239 is a kind of ``file'' that is essentially a pointer to another file
1240 name.  Unlike hard links, symbolic links can be made to directories or
1241 across file systems with no restrictions.  You can also make a symbolic
1242 link to a name which is not the name of any file.  (Opening this link
1243 will fail until a file by that name is created.)  Likewise, if the
1244 symbolic link points to an existing file which is later deleted, the
1245 symbolic link continues to point to the same file name even though the
1246 name no longer names any file.
1248 The reason symbolic links work the way they do is that special things
1249 happen when you try to open the link.  The @code{open} function realizes
1250 you have specified the name of a link, reads the file name contained in
1251 the link, and opens that file name instead.  The @code{stat} function
1252 likewise operates on the file that the symbolic link points to, instead
1253 of on the link itself.
1255 By contrast, other operations such as deleting or renaming the file
1256 operate on the link itself.  The functions @code{readlink} and
1257 @code{lstat} also refrain from following symbolic links, because their
1258 purpose is to obtain information about the link.  @code{link}, the
1259 function that makes a hard link, does too.  It makes a hard link to the
1260 symbolic link, which one rarely wants.
1262 Some systems have, for some functions operating on files, a limit on
1263 how many symbolic links are followed when resolving a path name.  The
1264 limit if it exists is published in the @file{sys/param.h} header file.
1266 @comment sys/param.h
1267 @comment BSD
1268 @deftypevr Macro int MAXSYMLINKS
1270 The macro @code{MAXSYMLINKS} specifies how many symlinks some function
1271 will follow before returning @code{ELOOP}.  Not all functions behave the
1272 same and this value is not the same as that returned for
1273 @code{_SC_SYMLOOP} by @code{sysconf}.  In fact, the @code{sysconf}
1274 result can indicate that there is no fixed limit although
1275 @code{MAXSYMLINKS} exists and has a finite value.
1276 @end deftypevr
1278 Prototypes for most of the functions listed in this section are in
1279 @file{unistd.h}.
1280 @pindex unistd.h
1282 @comment unistd.h
1283 @comment BSD
1284 @deftypefun int symlink (const char *@var{oldname}, const char *@var{newname})
1285 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1286 The @code{symlink} function makes a symbolic link to @var{oldname} named
1287 @var{newname}.
1289 The normal return value from @code{symlink} is @code{0}.  A return value
1290 of @code{-1} indicates an error.  In addition to the usual file name
1291 syntax errors (@pxref{File Name Errors}), the following @code{errno}
1292 error conditions are defined for this function:
1294 @table @code
1295 @item EEXIST
1296 There is already an existing file named @var{newname}.
1298 @item EROFS
1299 The file @var{newname} would exist on a read-only file system.
1301 @item ENOSPC
1302 The directory or file system cannot be extended to make the new link.
1304 @item EIO
1305 A hardware error occurred while reading or writing data on the disk.
1307 @ignore
1308 @comment not sure about these
1309 @item ELOOP
1310 There are too many levels of indirection.  This can be the result of
1311 circular symbolic links to directories.
1313 @item EDQUOT
1314 The new link can't be created because the user's disk quota has been
1315 exceeded.
1316 @end ignore
1317 @end table
1318 @end deftypefun
1320 @comment unistd.h
1321 @comment BSD
1322 @deftypefun ssize_t readlink (const char *@var{filename}, char *@var{buffer}, size_t @var{size})
1323 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1324 The @code{readlink} function gets the value of the symbolic link
1325 @var{filename}.  The file name that the link points to is copied into
1326 @var{buffer}.  This file name string is @emph{not} null-terminated;
1327 @code{readlink} normally returns the number of characters copied.  The
1328 @var{size} argument specifies the maximum number of characters to copy,
1329 usually the allocation size of @var{buffer}.
1331 If the return value equals @var{size}, you cannot tell whether or not
1332 there was room to return the entire name.  So make a bigger buffer and
1333 call @code{readlink} again.  Here is an example:
1335 @smallexample
1336 char *
1337 readlink_malloc (const char *filename)
1339   int size = 100;
1340   char *buffer = NULL;
1342   while (1)
1343     @{
1344       buffer = (char *) xrealloc (buffer, size);
1345       int nchars = readlink (filename, buffer, size);
1346       if (nchars < 0)
1347         @{
1348           free (buffer);
1349           return NULL;
1350         @}
1351       if (nchars < size)
1352         return buffer;
1353       size *= 2;
1354     @}
1356 @end smallexample
1358 @c @group  Invalid outside example.
1359 A value of @code{-1} is returned in case of error.  In addition to the
1360 usual file name errors (@pxref{File Name Errors}), the following
1361 @code{errno} error conditions are defined for this function:
1363 @table @code
1364 @item EINVAL
1365 The named file is not a symbolic link.
1367 @item EIO
1368 A hardware error occurred while reading or writing data on the disk.
1369 @end table
1370 @c @end group
1371 @end deftypefun
1373 In some situations it is desirable to resolve all the
1374 symbolic links to get the real
1375 name of a file where no prefix names a symbolic link which is followed
1376 and no filename in the path is @code{.} or @code{..}.  This is for
1377 instance desirable if files have to be compared in which case different
1378 names can refer to the same inode.
1380 @comment stdlib.h
1381 @comment GNU
1382 @deftypefun {char *} canonicalize_file_name (const char *@var{name})
1383 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
1384 @c Calls realpath.
1386 The @code{canonicalize_file_name} function returns the absolute name of
1387 the file named by @var{name} which contains no @code{.}, @code{..}
1388 components nor any repeated path separators (@code{/}) or symlinks.  The
1389 result is passed back as the return value of the function in a block of
1390 memory allocated with @code{malloc}.  If the result is not used anymore
1391 the memory should be freed with a call to @code{free}.
1393 If any of the path components are missing the function returns a NULL
1394 pointer.  This is also what is returned if the length of the path
1395 reaches or exceeds @code{PATH_MAX} characters.  In any case
1396 @code{errno} is set accordingly.
1398 @table @code
1399 @item ENAMETOOLONG
1400 The resulting path is too long.  This error only occurs on systems which
1401 have a limit on the file name length.
1403 @item EACCES
1404 At least one of the path components is not readable.
1406 @item ENOENT
1407 The input file name is empty.
1409 @item ENOENT
1410 At least one of the path components does not exist.
1412 @item ELOOP
1413 More than @code{MAXSYMLINKS} many symlinks have been followed.
1414 @end table
1416 This function is a GNU extension and is declared in @file{stdlib.h}.
1417 @end deftypefun
1419 The Unix standard includes a similar function which differs from
1420 @code{canonicalize_file_name} in that the user has to provide the buffer
1421 where the result is placed in.
1423 @comment stdlib.h
1424 @comment XPG
1425 @deftypefun {char *} realpath (const char *restrict @var{name}, char *restrict @var{resolved})
1426 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
1427 @c Calls malloc, realloc, getcwd, lxstat64, readlink, alloca.
1429 A call to @code{realpath} where the @var{resolved} parameter is
1430 @code{NULL} behaves exactly like @code{canonicalize_file_name}.  The
1431 function allocates a buffer for the file name and returns a pointer to
1432 it.  If @var{resolved} is not @code{NULL} it points to a buffer into
1433 which the result is copied.  It is the callers responsibility to
1434 allocate a buffer which is large enough.  On systems which define
1435 @code{PATH_MAX} this means the buffer must be large enough for a
1436 pathname of this size.  For systems without limitations on the pathname
1437 length the requirement cannot be met and programs should not call
1438 @code{realpath} with anything but @code{NULL} for the second parameter.
1440 One other difference is that the buffer @var{resolved} (if nonzero) will
1441 contain the part of the path component which does not exist or is not
1442 readable if the function returns @code{NULL} and @code{errno} is set to
1443 @code{EACCES} or @code{ENOENT}.
1445 This function is declared in @file{stdlib.h}.
1446 @end deftypefun
1448 The advantage of using this function is that it is more widely
1449 available.  The drawback is that it reports failures for long paths on
1450 systems which have no limits on the file name length.
1452 @node Deleting Files
1453 @section Deleting Files
1454 @cindex deleting a file
1455 @cindex removing a file
1456 @cindex unlinking a file
1458 You can delete a file with @code{unlink} or @code{remove}.
1460 Deletion actually deletes a file name.  If this is the file's only name,
1461 then the file is deleted as well.  If the file has other remaining names
1462 (@pxref{Hard Links}), it remains accessible under those names.
1464 @comment unistd.h
1465 @comment POSIX.1
1466 @deftypefun int unlink (const char *@var{filename})
1467 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1468 The @code{unlink} function deletes the file name @var{filename}.  If
1469 this is a file's sole name, the file itself is also deleted.  (Actually,
1470 if any process has the file open when this happens, deletion is
1471 postponed until all processes have closed the file.)
1473 @pindex unistd.h
1474 The function @code{unlink} is declared in the header file @file{unistd.h}.
1476 This function returns @code{0} on successful completion, and @code{-1}
1477 on error.  In addition to the usual file name errors
1478 (@pxref{File Name Errors}), the following @code{errno} error conditions are
1479 defined for this function:
1481 @table @code
1482 @item EACCES
1483 Write permission is denied for the directory from which the file is to be
1484 removed, or the directory has the sticky bit set and you do not own the file.
1486 @item EBUSY
1487 This error indicates that the file is being used by the system in such a
1488 way that it can't be unlinked.  For example, you might see this error if
1489 the file name specifies the root directory or a mount point for a file
1490 system.
1492 @item ENOENT
1493 The file name to be deleted doesn't exist.
1495 @item EPERM
1496 On some systems @code{unlink} cannot be used to delete the name of a
1497 directory, or at least can only be used this way by a privileged user.
1498 To avoid such problems, use @code{rmdir} to delete directories.  (On
1499 @gnulinuxhurdsystems{} @code{unlink} can never delete the name of a directory.)
1501 @item EROFS
1502 The directory containing the file name to be deleted is on a read-only
1503 file system and can't be modified.
1504 @end table
1505 @end deftypefun
1507 @comment unistd.h
1508 @comment POSIX.1
1509 @deftypefun int rmdir (const char *@var{filename})
1510 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1511 @cindex directories, deleting
1512 @cindex deleting a directory
1513 The @code{rmdir} function deletes a directory.  The directory must be
1514 empty before it can be removed; in other words, it can only contain
1515 entries for @file{.} and @file{..}.
1517 In most other respects, @code{rmdir} behaves like @code{unlink}.  There
1518 are two additional @code{errno} error conditions defined for
1519 @code{rmdir}:
1521 @table @code
1522 @item ENOTEMPTY
1523 @itemx EEXIST
1524 The directory to be deleted is not empty.
1525 @end table
1527 These two error codes are synonymous; some systems use one, and some use
1528 the other.  @gnulinuxhurdsystems{} always use @code{ENOTEMPTY}.
1530 The prototype for this function is declared in the header file
1531 @file{unistd.h}.
1532 @pindex unistd.h
1533 @end deftypefun
1535 @comment stdio.h
1536 @comment ISO
1537 @deftypefun int remove (const char *@var{filename})
1538 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1539 @c Calls unlink and rmdir.
1540 This is the @w{ISO C} function to remove a file.  It works like
1541 @code{unlink} for files and like @code{rmdir} for directories.
1542 @code{remove} is declared in @file{stdio.h}.
1543 @pindex stdio.h
1544 @end deftypefun
1546 @node Renaming Files
1547 @section Renaming Files
1549 The @code{rename} function is used to change a file's name.
1551 @cindex renaming a file
1552 @comment stdio.h
1553 @comment ISO
1554 @deftypefun int rename (const char *@var{oldname}, const char *@var{newname})
1555 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1556 @c In the absence of a rename syscall, there's an emulation with link
1557 @c and unlink, but it's racy, even more so if newname exists and is
1558 @c unlinked first.
1559 The @code{rename} function renames the file @var{oldname} to
1560 @var{newname}.  The file formerly accessible under the name
1561 @var{oldname} is afterwards accessible as @var{newname} instead.  (If
1562 the file had any other names aside from @var{oldname}, it continues to
1563 have those names.)
1565 The directory containing the name @var{newname} must be on the same file
1566 system as the directory containing the name @var{oldname}.
1568 One special case for @code{rename} is when @var{oldname} and
1569 @var{newname} are two names for the same file.  The consistent way to
1570 handle this case is to delete @var{oldname}.  However, in this case
1571 POSIX requires that @code{rename} do nothing and report success---which
1572 is inconsistent.  We don't know what your operating system will do.
1574 If @var{oldname} is not a directory, then any existing file named
1575 @var{newname} is removed during the renaming operation.  However, if
1576 @var{newname} is the name of a directory, @code{rename} fails in this
1577 case.
1579 If @var{oldname} is a directory, then either @var{newname} must not
1580 exist or it must name a directory that is empty.  In the latter case,
1581 the existing directory named @var{newname} is deleted first.  The name
1582 @var{newname} must not specify a subdirectory of the directory
1583 @code{oldname} which is being renamed.
1585 One useful feature of @code{rename} is that the meaning of @var{newname}
1586 changes ``atomically'' from any previously existing file by that name to
1587 its new meaning (i.e., the file that was called @var{oldname}).  There is
1588 no instant at which @var{newname} is non-existent ``in between'' the old
1589 meaning and the new meaning.  If there is a system crash during the
1590 operation, it is possible for both names to still exist; but
1591 @var{newname} will always be intact if it exists at all.
1593 If @code{rename} fails, it returns @code{-1}.  In addition to the usual
1594 file name errors (@pxref{File Name Errors}), the following
1595 @code{errno} error conditions are defined for this function:
1597 @table @code
1598 @item EACCES
1599 One of the directories containing @var{newname} or @var{oldname}
1600 refuses write permission; or @var{newname} and @var{oldname} are
1601 directories and write permission is refused for one of them.
1603 @item EBUSY
1604 A directory named by @var{oldname} or @var{newname} is being used by
1605 the system in a way that prevents the renaming from working.  This includes
1606 directories that are mount points for filesystems, and directories
1607 that are the current working directories of processes.
1609 @item ENOTEMPTY
1610 @itemx EEXIST
1611 The directory @var{newname} isn't empty.  @gnulinuxhurdsystems{} always return
1612 @code{ENOTEMPTY} for this, but some other systems return @code{EEXIST}.
1614 @item EINVAL
1615 @var{oldname} is a directory that contains @var{newname}.
1617 @item EISDIR
1618 @var{newname} is a directory but the @var{oldname} isn't.
1620 @item EMLINK
1621 The parent directory of @var{newname} would have too many links
1622 (entries).
1624 @item ENOENT
1625 The file @var{oldname} doesn't exist.
1627 @item ENOSPC
1628 The directory that would contain @var{newname} has no room for another
1629 entry, and there is no space left in the file system to expand it.
1631 @item EROFS
1632 The operation would involve writing to a directory on a read-only file
1633 system.
1635 @item EXDEV
1636 The two file names @var{newname} and @var{oldname} are on different
1637 file systems.
1638 @end table
1639 @end deftypefun
1641 @node Creating Directories
1642 @section Creating Directories
1643 @cindex creating a directory
1644 @cindex directories, creating
1646 @pindex mkdir
1647 Directories are created with the @code{mkdir} function.  (There is also
1648 a shell command @code{mkdir} which does the same thing.)
1649 @c !!! umask
1651 @comment sys/stat.h
1652 @comment POSIX.1
1653 @deftypefun int mkdir (const char *@var{filename}, mode_t @var{mode})
1654 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1655 The @code{mkdir} function creates a new, empty directory with name
1656 @var{filename}.
1658 The argument @var{mode} specifies the file permissions for the new
1659 directory file.  @xref{Permission Bits}, for more information about
1660 this.
1662 A return value of @code{0} indicates successful completion, and
1663 @code{-1} indicates failure.  In addition to the usual file name syntax
1664 errors (@pxref{File Name Errors}), the following @code{errno} error
1665 conditions are defined for this function:
1667 @table @code
1668 @item EACCES
1669 Write permission is denied for the parent directory in which the new
1670 directory is to be added.
1672 @item EEXIST
1673 A file named @var{filename} already exists.
1675 @item EMLINK
1676 The parent directory has too many links (entries).
1678 Well-designed file systems never report this error, because they permit
1679 more links than your disk could possibly hold.  However, you must still
1680 take account of the possibility of this error, as it could result from
1681 network access to a file system on another machine.
1683 @item ENOSPC
1684 The file system doesn't have enough room to create the new directory.
1686 @item EROFS
1687 The parent directory of the directory being created is on a read-only
1688 file system and cannot be modified.
1689 @end table
1691 To use this function, your program should include the header file
1692 @file{sys/stat.h}.
1693 @pindex sys/stat.h
1694 @end deftypefun
1696 @node File Attributes
1697 @section File Attributes
1699 @pindex ls
1700 When you issue an @samp{ls -l} shell command on a file, it gives you
1701 information about the size of the file, who owns it, when it was last
1702 modified, etc.  These are called the @dfn{file attributes}, and are
1703 associated with the file itself and not a particular one of its names.
1705 This section contains information about how you can inquire about and
1706 modify the attributes of a file.
1708 @menu
1709 * Attribute Meanings::          The names of the file attributes,
1710                                  and what their values mean.
1711 * Reading Attributes::          How to read the attributes of a file.
1712 * Testing File Type::           Distinguishing ordinary files,
1713                                  directories, links@dots{}
1714 * File Owner::                  How ownership for new files is determined,
1715                                  and how to change it.
1716 * Permission Bits::             How information about a file's access
1717                                  mode is stored.
1718 * Access Permission::           How the system decides who can access a file.
1719 * Setting Permissions::         How permissions for new files are assigned,
1720                                  and how to change them.
1721 * Testing File Access::         How to find out if your process can
1722                                  access a file.
1723 * File Times::                  About the time attributes of a file.
1724 * File Size::                   Manually changing the size of a file.
1725 * Storage Allocation::          Allocate backing storage for files.
1726 @end menu
1728 @node Attribute Meanings
1729 @subsection The meaning of the File Attributes
1730 @cindex status of a file
1731 @cindex attributes of a file
1732 @cindex file attributes
1734 When you read the attributes of a file, they come back in a structure
1735 called @code{struct stat}.  This section describes the names of the
1736 attributes, their data types, and what they mean.  For the functions
1737 to read the attributes of a file, see @ref{Reading Attributes}.
1739 The header file @file{sys/stat.h} declares all the symbols defined
1740 in this section.
1741 @pindex sys/stat.h
1743 @comment sys/stat.h
1744 @comment POSIX.1
1745 @deftp {Data Type} {struct stat}
1746 The @code{stat} structure type is used to return information about the
1747 attributes of a file.  It contains at least the following members:
1749 @table @code
1750 @item mode_t st_mode
1751 Specifies the mode of the file.  This includes file type information
1752 (@pxref{Testing File Type}) and the file permission bits
1753 (@pxref{Permission Bits}).
1755 @item ino_t st_ino
1756 The file serial number, which distinguishes this file from all other
1757 files on the same device.
1759 @item dev_t st_dev
1760 Identifies the device containing the file.  The @code{st_ino} and
1761 @code{st_dev}, taken together, uniquely identify the file.  The
1762 @code{st_dev} value is not necessarily consistent across reboots or
1763 system crashes, however.
1765 @item nlink_t st_nlink
1766 The number of hard links to the file.  This count keeps track of how
1767 many directories have entries for this file.  If the count is ever
1768 decremented to zero, then the file itself is discarded as soon as no
1769 process still holds it open.  Symbolic links are not counted in the
1770 total.
1772 @item uid_t st_uid
1773 The user ID of the file's owner.  @xref{File Owner}.
1775 @item gid_t st_gid
1776 The group ID of the file.  @xref{File Owner}.
1778 @item off_t st_size
1779 This specifies the size of a regular file in bytes.  For files that are
1780 really devices this field isn't usually meaningful.  For symbolic links
1781 this specifies the length of the file name the link refers to.
1783 @item time_t st_atime
1784 This is the last access time for the file.  @xref{File Times}.
1786 @item unsigned long int st_atime_usec
1787 This is the fractional part of the last access time for the file.
1788 @xref{File Times}.
1790 @item time_t st_mtime
1791 This is the time of the last modification to the contents of the file.
1792 @xref{File Times}.
1794 @item unsigned long int st_mtime_usec
1795 This is the fractional part of the time of the last modification to the
1796 contents of the file.  @xref{File Times}.
1798 @item time_t st_ctime
1799 This is the time of the last modification to the attributes of the file.
1800 @xref{File Times}.
1802 @item unsigned long int st_ctime_usec
1803 This is the fractional part of the time of the last modification to the
1804 attributes of the file.  @xref{File Times}.
1806 @c !!! st_rdev
1807 @item blkcnt_t st_blocks
1808 This is the amount of disk space that the file occupies, measured in
1809 units of 512-byte blocks.
1811 The number of disk blocks is not strictly proportional to the size of
1812 the file, for two reasons: the file system may use some blocks for
1813 internal record keeping; and the file may be sparse---it may have
1814 ``holes'' which contain zeros but do not actually take up space on the
1815 disk.
1817 You can tell (approximately) whether a file is sparse by comparing this
1818 value with @code{st_size}, like this:
1820 @smallexample
1821 (st.st_blocks * 512 < st.st_size)
1822 @end smallexample
1824 This test is not perfect because a file that is just slightly sparse
1825 might not be detected as sparse at all.  For practical applications,
1826 this is not a problem.
1828 @item unsigned int st_blksize
1829 The optimal block size for reading or writing this file, in bytes.  You
1830 might use this size for allocating the buffer space for reading or
1831 writing the file.  (This is unrelated to @code{st_blocks}.)
1832 @end table
1833 @end deftp
1835 The extensions for the Large File Support (LFS) require, even on 32-bit
1836 machines, types which can handle file sizes up to @twoexp{63}.
1837 Therefore a new definition of @code{struct stat} is necessary.
1839 @comment sys/stat.h
1840 @comment LFS
1841 @deftp {Data Type} {struct stat64}
1842 The members of this type are the same and have the same names as those
1843 in @code{struct stat}.  The only difference is that the members
1844 @code{st_ino}, @code{st_size}, and @code{st_blocks} have a different
1845 type to support larger values.
1847 @table @code
1848 @item mode_t st_mode
1849 Specifies the mode of the file.  This includes file type information
1850 (@pxref{Testing File Type}) and the file permission bits
1851 (@pxref{Permission Bits}).
1853 @item ino64_t st_ino
1854 The file serial number, which distinguishes this file from all other
1855 files on the same device.
1857 @item dev_t st_dev
1858 Identifies the device containing the file.  The @code{st_ino} and
1859 @code{st_dev}, taken together, uniquely identify the file.  The
1860 @code{st_dev} value is not necessarily consistent across reboots or
1861 system crashes, however.
1863 @item nlink_t st_nlink
1864 The number of hard links to the file.  This count keeps track of how
1865 many directories have entries for this file.  If the count is ever
1866 decremented to zero, then the file itself is discarded as soon as no
1867 process still holds it open.  Symbolic links are not counted in the
1868 total.
1870 @item uid_t st_uid
1871 The user ID of the file's owner.  @xref{File Owner}.
1873 @item gid_t st_gid
1874 The group ID of the file.  @xref{File Owner}.
1876 @item off64_t st_size
1877 This specifies the size of a regular file in bytes.  For files that are
1878 really devices this field isn't usually meaningful.  For symbolic links
1879 this specifies the length of the file name the link refers to.
1881 @item time_t st_atime
1882 This is the last access time for the file.  @xref{File Times}.
1884 @item unsigned long int st_atime_usec
1885 This is the fractional part of the last access time for the file.
1886 @xref{File Times}.
1888 @item time_t st_mtime
1889 This is the time of the last modification to the contents of the file.
1890 @xref{File Times}.
1892 @item unsigned long int st_mtime_usec
1893 This is the fractional part of the time of the last modification to the
1894 contents of the file.  @xref{File Times}.
1896 @item time_t st_ctime
1897 This is the time of the last modification to the attributes of the file.
1898 @xref{File Times}.
1900 @item unsigned long int st_ctime_usec
1901 This is the fractional part of the time of the last modification to the
1902 attributes of the file.  @xref{File Times}.
1904 @c !!! st_rdev
1905 @item blkcnt64_t st_blocks
1906 This is the amount of disk space that the file occupies, measured in
1907 units of 512-byte blocks.
1909 @item unsigned int st_blksize
1910 The optimal block size for reading of writing this file, in bytes.  You
1911 might use this size for allocating the buffer space for reading of
1912 writing the file.  (This is unrelated to @code{st_blocks}.)
1913 @end table
1914 @end deftp
1916 Some of the file attributes have special data type names which exist
1917 specifically for those attributes.  (They are all aliases for well-known
1918 integer types that you know and love.)  These typedef names are defined
1919 in the header file @file{sys/types.h} as well as in @file{sys/stat.h}.
1920 Here is a list of them.
1922 @comment sys/types.h
1923 @comment POSIX.1
1924 @deftp {Data Type} mode_t
1925 This is an integer data type used to represent file modes.  In
1926 @theglibc{}, this is an unsigned type no narrower than @code{unsigned
1927 int}.
1928 @end deftp
1930 @cindex inode number
1931 @comment sys/types.h
1932 @comment POSIX.1
1933 @deftp {Data Type} ino_t
1934 This is an unsigned integer type used to represent file serial numbers.
1935 (In Unix jargon, these are sometimes called @dfn{inode numbers}.)
1936 In @theglibc{}, this type is no narrower than @code{unsigned int}.
1938 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1939 is transparently replaced by @code{ino64_t}.
1940 @end deftp
1942 @comment sys/types.h
1943 @comment Unix98
1944 @deftp {Data Type} ino64_t
1945 This is an unsigned integer type used to represent file serial numbers
1946 for the use in LFS.  In @theglibc{}, this type is no narrower than
1947 @code{unsigned int}.
1949 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1950 available under the name @code{ino_t}.
1951 @end deftp
1953 @comment sys/types.h
1954 @comment POSIX.1
1955 @deftp {Data Type} dev_t
1956 This is an arithmetic data type used to represent file device numbers.
1957 In @theglibc{}, this is an integer type no narrower than @code{int}.
1958 @end deftp
1960 @comment sys/types.h
1961 @comment POSIX.1
1962 @deftp {Data Type} nlink_t
1963 This is an integer type used to represent file link counts.
1964 @end deftp
1966 @comment sys/types.h
1967 @comment Unix98
1968 @deftp {Data Type} blkcnt_t
1969 This is a signed integer type used to represent block counts.
1970 In @theglibc{}, this type is no narrower than @code{int}.
1972 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1973 is transparently replaced by @code{blkcnt64_t}.
1974 @end deftp
1976 @comment sys/types.h
1977 @comment Unix98
1978 @deftp {Data Type} blkcnt64_t
1979 This is a signed integer type used to represent block counts for the
1980 use in LFS.  In @theglibc{}, this type is no narrower than @code{int}.
1982 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1983 available under the name @code{blkcnt_t}.
1984 @end deftp
1986 @node Reading Attributes
1987 @subsection Reading the Attributes of a File
1989 To examine the attributes of files, use the functions @code{stat},
1990 @code{fstat} and @code{lstat}.  They return the attribute information in
1991 a @code{struct stat} object.  All three functions are declared in the
1992 header file @file{sys/stat.h}.
1994 @comment sys/stat.h
1995 @comment POSIX.1
1996 @deftypefun int stat (const char *@var{filename}, struct stat *@var{buf})
1997 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1998 The @code{stat} function returns information about the attributes of the
1999 file named by @w{@var{filename}} in the structure pointed to by @var{buf}.
2001 If @var{filename} is the name of a symbolic link, the attributes you get
2002 describe the file that the link points to.  If the link points to a
2003 nonexistent file name, then @code{stat} fails reporting a nonexistent
2004 file.
2006 The return value is @code{0} if the operation is successful, or
2007 @code{-1} on failure.  In addition to the usual file name errors
2008 (@pxref{File Name Errors}, the following @code{errno} error conditions
2009 are defined for this function:
2011 @table @code
2012 @item ENOENT
2013 The file named by @var{filename} doesn't exist.
2014 @end table
2016 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2017 function is in fact @code{stat64} since the LFS interface transparently
2018 replaces the normal implementation.
2019 @end deftypefun
2021 @comment sys/stat.h
2022 @comment Unix98
2023 @deftypefun int stat64 (const char *@var{filename}, struct stat64 *@var{buf})
2024 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2025 This function is similar to @code{stat} but it is also able to work on
2026 files larger than @twoexp{31} bytes on 32-bit systems.  To be able to do
2027 this the result is stored in a variable of type @code{struct stat64} to
2028 which @var{buf} must point.
2030 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2031 function is available under the name @code{stat} and so transparently
2032 replaces the interface for small files on 32-bit machines.
2033 @end deftypefun
2035 @comment sys/stat.h
2036 @comment POSIX.1
2037 @deftypefun int fstat (int @var{filedes}, struct stat *@var{buf})
2038 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2039 The @code{fstat} function is like @code{stat}, except that it takes an
2040 open file descriptor as an argument instead of a file name.
2041 @xref{Low-Level I/O}.
2043 Like @code{stat}, @code{fstat} returns @code{0} on success and @code{-1}
2044 on failure.  The following @code{errno} error conditions are defined for
2045 @code{fstat}:
2047 @table @code
2048 @item EBADF
2049 The @var{filedes} argument is not a valid file descriptor.
2050 @end table
2052 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2053 function is in fact @code{fstat64} since the LFS interface transparently
2054 replaces the normal implementation.
2055 @end deftypefun
2057 @comment sys/stat.h
2058 @comment Unix98
2059 @deftypefun int fstat64 (int @var{filedes}, struct stat64 *@var{buf})
2060 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2061 This function is similar to @code{fstat} but is able to work on large
2062 files on 32-bit platforms.  For large files the file descriptor
2063 @var{filedes} should be obtained by @code{open64} or @code{creat64}.
2064 The @var{buf} pointer points to a variable of type @code{struct stat64}
2065 which is able to represent the larger values.
2067 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2068 function is available under the name @code{fstat} and so transparently
2069 replaces the interface for small files on 32-bit machines.
2070 @end deftypefun
2072 @c fstatat will call alloca and snprintf if the syscall is not
2073 @c available.
2074 @c @safety{@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2076 @comment sys/stat.h
2077 @comment BSD
2078 @deftypefun int lstat (const char *@var{filename}, struct stat *@var{buf})
2079 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2080 @c Direct system call through lxstat, sometimes with an xstat conv call
2081 @c afterwards.
2082 The @code{lstat} function is like @code{stat}, except that it does not
2083 follow symbolic links.  If @var{filename} is the name of a symbolic
2084 link, @code{lstat} returns information about the link itself; otherwise
2085 @code{lstat} works like @code{stat}.  @xref{Symbolic Links}.
2087 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2088 function is in fact @code{lstat64} since the LFS interface transparently
2089 replaces the normal implementation.
2090 @end deftypefun
2092 @comment sys/stat.h
2093 @comment Unix98
2094 @deftypefun int lstat64 (const char *@var{filename}, struct stat64 *@var{buf})
2095 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2096 @c Direct system call through lxstat64, sometimes with an xstat conv
2097 @c call afterwards.
2098 This function is similar to @code{lstat} but it is also able to work on
2099 files larger than @twoexp{31} bytes on 32-bit systems.  To be able to do
2100 this the result is stored in a variable of type @code{struct stat64} to
2101 which @var{buf} must point.
2103 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2104 function is available under the name @code{lstat} and so transparently
2105 replaces the interface for small files on 32-bit machines.
2106 @end deftypefun
2108 @node Testing File Type
2109 @subsection Testing the Type of a File
2111 The @dfn{file mode}, stored in the @code{st_mode} field of the file
2112 attributes, contains two kinds of information: the file type code, and
2113 the access permission bits.  This section discusses only the type code,
2114 which you can use to tell whether the file is a directory, socket,
2115 symbolic link, and so on.  For details about access permissions see
2116 @ref{Permission Bits}.
2118 There are two ways you can access the file type information in a file
2119 mode.  Firstly, for each file type there is a @dfn{predicate macro}
2120 which examines a given file mode and returns whether it is of that type
2121 or not.  Secondly, you can mask out the rest of the file mode to leave
2122 just the file type code, and compare this against constants for each of
2123 the supported file types.
2125 All of the symbols listed in this section are defined in the header file
2126 @file{sys/stat.h}.
2127 @pindex sys/stat.h
2129 The following predicate macros test the type of a file, given the value
2130 @var{m} which is the @code{st_mode} field returned by @code{stat} on
2131 that file:
2133 @comment sys/stat.h
2134 @comment POSIX
2135 @deftypefn Macro int S_ISDIR (mode_t @var{m})
2136 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2137 This macro returns non-zero if the file is a directory.
2138 @end deftypefn
2140 @comment sys/stat.h
2141 @comment POSIX
2142 @deftypefn Macro int S_ISCHR (mode_t @var{m})
2143 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2144 This macro returns non-zero if the file is a character special file (a
2145 device like a terminal).
2146 @end deftypefn
2148 @comment sys/stat.h
2149 @comment POSIX
2150 @deftypefn Macro int S_ISBLK (mode_t @var{m})
2151 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2152 This macro returns non-zero if the file is a block special file (a device
2153 like a disk).
2154 @end deftypefn
2156 @comment sys/stat.h
2157 @comment POSIX
2158 @deftypefn Macro int S_ISREG (mode_t @var{m})
2159 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2160 This macro returns non-zero if the file is a regular file.
2161 @end deftypefn
2163 @comment sys/stat.h
2164 @comment POSIX
2165 @deftypefn Macro int S_ISFIFO (mode_t @var{m})
2166 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2167 This macro returns non-zero if the file is a FIFO special file, or a
2168 pipe.  @xref{Pipes and FIFOs}.
2169 @end deftypefn
2171 @comment sys/stat.h
2172 @comment GNU
2173 @deftypefn Macro int S_ISLNK (mode_t @var{m})
2174 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2175 This macro returns non-zero if the file is a symbolic link.
2176 @xref{Symbolic Links}.
2177 @end deftypefn
2179 @comment sys/stat.h
2180 @comment GNU
2181 @deftypefn Macro int S_ISSOCK (mode_t @var{m})
2182 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2183 This macro returns non-zero if the file is a socket.  @xref{Sockets}.
2184 @end deftypefn
2186 An alternate non-POSIX method of testing the file type is supported for
2187 compatibility with BSD.  The mode can be bitwise AND-ed with
2188 @code{S_IFMT} to extract the file type code, and compared to the
2189 appropriate constant.  For example,
2191 @smallexample
2192 S_ISCHR (@var{mode})
2193 @end smallexample
2195 @noindent
2196 is equivalent to:
2198 @smallexample
2199 ((@var{mode} & S_IFMT) == S_IFCHR)
2200 @end smallexample
2202 @comment sys/stat.h
2203 @comment BSD
2204 @deftypevr Macro int S_IFMT
2205 This is a bit mask used to extract the file type code from a mode value.
2206 @end deftypevr
2208 These are the symbolic names for the different file type codes:
2210 @vtable @code
2211 @comment sys/stat.h
2212 @comment BSD
2213 @item S_IFDIR
2214 This is the file type constant of a directory file.
2216 @comment sys/stat.h
2217 @comment BSD
2218 @item S_IFCHR
2219 This is the file type constant of a character-oriented device file.
2221 @comment sys/stat.h
2222 @comment BSD
2223 @item S_IFBLK
2224 This is the file type constant of a block-oriented device file.
2226 @comment sys/stat.h
2227 @comment BSD
2228 @item S_IFREG
2229 This is the file type constant of a regular file.
2231 @comment sys/stat.h
2232 @comment BSD
2233 @item S_IFLNK
2234 This is the file type constant of a symbolic link.
2236 @comment sys/stat.h
2237 @comment BSD
2238 @item S_IFSOCK
2239 This is the file type constant of a socket.
2241 @comment sys/stat.h
2242 @comment BSD
2243 @item S_IFIFO
2244 This is the file type constant of a FIFO or pipe.
2245 @end vtable
2247 The POSIX.1b standard introduced a few more objects which possibly can
2248 be implemented as objects in the filesystem.  These are message queues,
2249 semaphores, and shared memory objects.  To allow differentiating these
2250 objects from other files the POSIX standard introduced three new test
2251 macros.  But unlike the other macros they do not take the value of the
2252 @code{st_mode} field as the parameter.  Instead they expect a pointer to
2253 the whole @code{struct stat} structure.
2255 @comment sys/stat.h
2256 @comment POSIX
2257 @deftypefn Macro int S_TYPEISMQ (struct stat *@var{s})
2258 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2259 If the system implements POSIX message queues as distinct objects and the
2260 file is a message queue object, this macro returns a non-zero value.
2261 In all other cases the result is zero.
2262 @end deftypefn
2264 @comment sys/stat.h
2265 @comment POSIX
2266 @deftypefn Macro int S_TYPEISSEM (struct stat *@var{s})
2267 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2268 If the system implements POSIX semaphores as distinct objects and the
2269 file is a semaphore object, this macro returns a non-zero value.
2270 In all other cases the result is zero.
2271 @end deftypefn
2273 @comment sys/stat.h
2274 @comment POSIX
2275 @deftypefn Macro int S_TYPEISSHM (struct stat *@var{s})
2276 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2277 If the system implements POSIX shared memory objects as distinct objects
2278 and the file is a shared memory object, this macro returns a non-zero
2279 value.  In all other cases the result is zero.
2280 @end deftypefn
2282 @node File Owner
2283 @subsection File Owner
2284 @cindex file owner
2285 @cindex owner of a file
2286 @cindex group owner of a file
2288 Every file has an @dfn{owner} which is one of the registered user names
2289 defined on the system.  Each file also has a @dfn{group} which is one of
2290 the defined groups.  The file owner can often be useful for showing you
2291 who edited the file (especially when you edit with GNU Emacs), but its
2292 main purpose is for access control.
2294 The file owner and group play a role in determining access because the
2295 file has one set of access permission bits for the owner, another set
2296 that applies to users who belong to the file's group, and a third set of
2297 bits that applies to everyone else.  @xref{Access Permission}, for the
2298 details of how access is decided based on this data.
2300 When a file is created, its owner is set to the effective user ID of the
2301 process that creates it (@pxref{Process Persona}).  The file's group ID
2302 may be set to either the effective group ID of the process, or the group
2303 ID of the directory that contains the file, depending on the system
2304 where the file is stored.  When you access a remote file system, it
2305 behaves according to its own rules, not according to the system your
2306 program is running on.  Thus, your program must be prepared to encounter
2307 either kind of behavior no matter what kind of system you run it on.
2309 @pindex chown
2310 @pindex chgrp
2311 You can change the owner and/or group owner of an existing file using
2312 the @code{chown} function.  This is the primitive for the @code{chown}
2313 and @code{chgrp} shell commands.
2315 @pindex unistd.h
2316 The prototype for this function is declared in @file{unistd.h}.
2318 @comment unistd.h
2319 @comment POSIX.1
2320 @deftypefun int chown (const char *@var{filename}, uid_t @var{owner}, gid_t @var{group})
2321 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2322 The @code{chown} function changes the owner of the file @var{filename} to
2323 @var{owner}, and its group owner to @var{group}.
2325 Changing the owner of the file on certain systems clears the set-user-ID
2326 and set-group-ID permission bits.  (This is because those bits may not
2327 be appropriate for the new owner.)  Other file permission bits are not
2328 changed.
2330 The return value is @code{0} on success and @code{-1} on failure.
2331 In addition to the usual file name errors (@pxref{File Name Errors}),
2332 the following @code{errno} error conditions are defined for this function:
2334 @table @code
2335 @item EPERM
2336 This process lacks permission to make the requested change.
2338 Only privileged users or the file's owner can change the file's group.
2339 On most file systems, only privileged users can change the file owner;
2340 some file systems allow you to change the owner if you are currently the
2341 owner.  When you access a remote file system, the behavior you encounter
2342 is determined by the system that actually holds the file, not by the
2343 system your program is running on.
2345 @xref{Options for Files}, for information about the
2346 @code{_POSIX_CHOWN_RESTRICTED} macro.
2348 @item EROFS
2349 The file is on a read-only file system.
2350 @end table
2351 @end deftypefun
2353 @comment unistd.h
2354 @comment BSD
2355 @deftypefun int fchown (int @var{filedes}, uid_t @var{owner}, gid_t @var{group})
2356 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2357 This is like @code{chown}, except that it changes the owner of the open
2358 file with descriptor @var{filedes}.
2360 The return value from @code{fchown} is @code{0} on success and @code{-1}
2361 on failure.  The following @code{errno} error codes are defined for this
2362 function:
2364 @table @code
2365 @item EBADF
2366 The @var{filedes} argument is not a valid file descriptor.
2368 @item EINVAL
2369 The @var{filedes} argument corresponds to a pipe or socket, not an ordinary
2370 file.
2372 @item EPERM
2373 This process lacks permission to make the requested change.  For details
2374 see @code{chmod} above.
2376 @item EROFS
2377 The file resides on a read-only file system.
2378 @end table
2379 @end deftypefun
2381 @node Permission Bits
2382 @subsection The Mode Bits for Access Permission
2384 The @dfn{file mode}, stored in the @code{st_mode} field of the file
2385 attributes, contains two kinds of information: the file type code, and
2386 the access permission bits.  This section discusses only the access
2387 permission bits, which control who can read or write the file.
2388 @xref{Testing File Type}, for information about the file type code.
2390 All of the symbols listed in this section are defined in the header file
2391 @file{sys/stat.h}.
2392 @pindex sys/stat.h
2394 @cindex file permission bits
2395 These symbolic constants are defined for the file mode bits that control
2396 access permission for the file:
2398 @vtable @code
2399 @comment sys/stat.h
2400 @comment POSIX.1
2401 @item S_IRUSR
2402 @comment sys/stat.h
2403 @comment BSD
2404 @itemx S_IREAD
2405 Read permission bit for the owner of the file.  On many systems this bit
2406 is 0400.  @code{S_IREAD} is an obsolete synonym provided for BSD
2407 compatibility.
2409 @comment sys/stat.h
2410 @comment POSIX.1
2411 @item S_IWUSR
2412 @comment sys/stat.h
2413 @comment BSD
2414 @itemx S_IWRITE
2415 Write permission bit for the owner of the file.  Usually 0200.
2416 @w{@code{S_IWRITE}} is an obsolete synonym provided for BSD compatibility.
2418 @comment sys/stat.h
2419 @comment POSIX.1
2420 @item S_IXUSR
2421 @comment sys/stat.h
2422 @comment BSD
2423 @itemx S_IEXEC
2424 Execute (for ordinary files) or search (for directories) permission bit
2425 for the owner of the file.  Usually 0100.  @code{S_IEXEC} is an obsolete
2426 synonym provided for BSD compatibility.
2428 @comment sys/stat.h
2429 @comment POSIX.1
2430 @item S_IRWXU
2431 This is equivalent to @samp{(S_IRUSR | S_IWUSR | S_IXUSR)}.
2433 @comment sys/stat.h
2434 @comment POSIX.1
2435 @item S_IRGRP
2436 Read permission bit for the group owner of the file.  Usually 040.
2438 @comment sys/stat.h
2439 @comment POSIX.1
2440 @item S_IWGRP
2441 Write permission bit for the group owner of the file.  Usually 020.
2443 @comment sys/stat.h
2444 @comment POSIX.1
2445 @item S_IXGRP
2446 Execute or search permission bit for the group owner of the file.
2447 Usually 010.
2449 @comment sys/stat.h
2450 @comment POSIX.1
2451 @item S_IRWXG
2452 This is equivalent to @samp{(S_IRGRP | S_IWGRP | S_IXGRP)}.
2454 @comment sys/stat.h
2455 @comment POSIX.1
2456 @item S_IROTH
2457 Read permission bit for other users.  Usually 04.
2459 @comment sys/stat.h
2460 @comment POSIX.1
2461 @item S_IWOTH
2462 Write permission bit for other users.  Usually 02.
2464 @comment sys/stat.h
2465 @comment POSIX.1
2466 @item S_IXOTH
2467 Execute or search permission bit for other users.  Usually 01.
2469 @comment sys/stat.h
2470 @comment POSIX.1
2471 @item S_IRWXO
2472 This is equivalent to @samp{(S_IROTH | S_IWOTH | S_IXOTH)}.
2474 @comment sys/stat.h
2475 @comment POSIX
2476 @item S_ISUID
2477 This is the set-user-ID on execute bit, usually 04000.
2478 @xref{How Change Persona}.
2480 @comment sys/stat.h
2481 @comment POSIX
2482 @item S_ISGID
2483 This is the set-group-ID on execute bit, usually 02000.
2484 @xref{How Change Persona}.
2486 @cindex sticky bit
2487 @comment sys/stat.h
2488 @comment BSD
2489 @item S_ISVTX
2490 This is the @dfn{sticky} bit, usually 01000.
2492 For a directory it gives permission to delete a file in that directory
2493 only if you own that file.  Ordinarily, a user can either delete all the
2494 files in a directory or cannot delete any of them (based on whether the
2495 user has write permission for the directory).  The same restriction
2496 applies---you must have both write permission for the directory and own
2497 the file you want to delete.  The one exception is that the owner of the
2498 directory can delete any file in the directory, no matter who owns it
2499 (provided the owner has given himself write permission for the
2500 directory).  This is commonly used for the @file{/tmp} directory, where
2501 anyone may create files but not delete files created by other users.
2503 Originally the sticky bit on an executable file modified the swapping
2504 policies of the system.  Normally, when a program terminated, its pages
2505 in core were immediately freed and reused.  If the sticky bit was set on
2506 the executable file, the system kept the pages in core for a while as if
2507 the program were still running.  This was advantageous for a program
2508 likely to be run many times in succession.  This usage is obsolete in
2509 modern systems.  When a program terminates, its pages always remain in
2510 core as long as there is no shortage of memory in the system.  When the
2511 program is next run, its pages will still be in core if no shortage
2512 arose since the last run.
2514 On some modern systems where the sticky bit has no useful meaning for an
2515 executable file, you cannot set the bit at all for a non-directory.
2516 If you try, @code{chmod} fails with @code{EFTYPE};
2517 @pxref{Setting Permissions}.
2519 Some systems (particularly SunOS) have yet another use for the sticky
2520 bit.  If the sticky bit is set on a file that is @emph{not} executable,
2521 it means the opposite: never cache the pages of this file at all.  The
2522 main use of this is for the files on an NFS server machine which are
2523 used as the swap area of diskless client machines.  The idea is that the
2524 pages of the file will be cached in the client's memory, so it is a
2525 waste of the server's memory to cache them a second time.  With this
2526 usage the sticky bit also implies that the filesystem may fail to record
2527 the file's modification time onto disk reliably (the idea being that
2528 no-one cares for a swap file).
2530 This bit is only available on BSD systems (and those derived from
2531 them).  Therefore one has to use the @code{_GNU_SOURCE} feature select
2532 macro, or not define any feature test macros, to get the definition
2533 (@pxref{Feature Test Macros}).
2534 @end vtable
2536 The actual bit values of the symbols are listed in the table above
2537 so you can decode file mode values when debugging your programs.
2538 These bit values are correct for most systems, but they are not
2539 guaranteed.
2541 @strong{Warning:} Writing explicit numbers for file permissions is bad
2542 practice.  Not only is it not portable, it also requires everyone who
2543 reads your program to remember what the bits mean.  To make your program
2544 clean use the symbolic names.
2546 @node Access Permission
2547 @subsection How Your Access to a File is Decided
2548 @cindex permission to access a file
2549 @cindex access permission for a file
2550 @cindex file access permission
2552 Recall that the operating system normally decides access permission for
2553 a file based on the effective user and group IDs of the process and its
2554 supplementary group IDs, together with the file's owner, group and
2555 permission bits.  These concepts are discussed in detail in @ref{Process
2556 Persona}.
2558 If the effective user ID of the process matches the owner user ID of the
2559 file, then permissions for read, write, and execute/search are
2560 controlled by the corresponding ``user'' (or ``owner'') bits.  Likewise,
2561 if any of the effective group ID or supplementary group IDs of the
2562 process matches the group owner ID of the file, then permissions are
2563 controlled by the ``group'' bits.  Otherwise, permissions are controlled
2564 by the ``other'' bits.
2566 Privileged users, like @samp{root}, can access any file regardless of
2567 its permission bits.  As a special case, for a file to be executable
2568 even by a privileged user, at least one of its execute bits must be set.
2570 @node Setting Permissions
2571 @subsection Assigning File Permissions
2573 @cindex file creation mask
2574 @cindex umask
2575 The primitive functions for creating files (for example, @code{open} or
2576 @code{mkdir}) take a @var{mode} argument, which specifies the file
2577 permissions to give the newly created file.  This mode is modified by
2578 the process's @dfn{file creation mask}, or @dfn{umask}, before it is
2579 used.
2581 The bits that are set in the file creation mask identify permissions
2582 that are always to be disabled for newly created files.  For example, if
2583 you set all the ``other'' access bits in the mask, then newly created
2584 files are not accessible at all to processes in the ``other'' category,
2585 even if the @var{mode} argument passed to the create function would
2586 permit such access.  In other words, the file creation mask is the
2587 complement of the ordinary access permissions you want to grant.
2589 Programs that create files typically specify a @var{mode} argument that
2590 includes all the permissions that make sense for the particular file.
2591 For an ordinary file, this is typically read and write permission for
2592 all classes of users.  These permissions are then restricted as
2593 specified by the individual user's own file creation mask.
2595 @findex chmod
2596 To change the permission of an existing file given its name, call
2597 @code{chmod}.  This function uses the specified permission bits and
2598 ignores the file creation mask.
2600 @pindex umask
2601 In normal use, the file creation mask is initialized by the user's login
2602 shell (using the @code{umask} shell command), and inherited by all
2603 subprocesses.  Application programs normally don't need to worry about
2604 the file creation mask.  It will automatically do what it is supposed to
2607 When your program needs to create a file and bypass the umask for its
2608 access permissions, the easiest way to do this is to use @code{fchmod}
2609 after opening the file, rather than changing the umask.  In fact,
2610 changing the umask is usually done only by shells.  They use the
2611 @code{umask} function.
2613 The functions in this section are declared in @file{sys/stat.h}.
2614 @pindex sys/stat.h
2616 @comment sys/stat.h
2617 @comment POSIX.1
2618 @deftypefun mode_t umask (mode_t @var{mask})
2619 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2620 The @code{umask} function sets the file creation mask of the current
2621 process to @var{mask}, and returns the previous value of the file
2622 creation mask.
2624 Here is an example showing how to read the mask with @code{umask}
2625 without changing it permanently:
2627 @smallexample
2628 mode_t
2629 read_umask (void)
2631   mode_t mask = umask (0);
2632   umask (mask);
2633   return mask;
2635 @end smallexample
2637 @noindent
2638 However, on @gnuhurdsystems{} it is better to use @code{getumask} if
2639 you just want to read the mask value, because it is reentrant.
2640 @end deftypefun
2642 @comment sys/stat.h
2643 @comment GNU
2644 @deftypefun mode_t getumask (void)
2645 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2646 Return the current value of the file creation mask for the current
2647 process.  This function is a GNU extension and is only available on
2648 @gnuhurdsystems{}.
2649 @end deftypefun
2651 @comment sys/stat.h
2652 @comment POSIX.1
2653 @deftypefun int chmod (const char *@var{filename}, mode_t @var{mode})
2654 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2655 The @code{chmod} function sets the access permission bits for the file
2656 named by @var{filename} to @var{mode}.
2658 If @var{filename} is a symbolic link, @code{chmod} changes the
2659 permissions of the file pointed to by the link, not those of the link
2660 itself.
2662 This function returns @code{0} if successful and @code{-1} if not.  In
2663 addition to the usual file name errors (@pxref{File Name
2664 Errors}), the following @code{errno} error conditions are defined for
2665 this function:
2667 @table @code
2668 @item ENOENT
2669 The named file doesn't exist.
2671 @item EPERM
2672 This process does not have permission to change the access permissions
2673 of this file.  Only the file's owner (as judged by the effective user ID
2674 of the process) or a privileged user can change them.
2676 @item EROFS
2677 The file resides on a read-only file system.
2679 @item EFTYPE
2680 @var{mode} has the @code{S_ISVTX} bit (the ``sticky bit'') set,
2681 and the named file is not a directory.  Some systems do not allow setting the
2682 sticky bit on non-directory files, and some do (and only some of those
2683 assign a useful meaning to the bit for non-directory files).
2685 You only get @code{EFTYPE} on systems where the sticky bit has no useful
2686 meaning for non-directory files, so it is always safe to just clear the
2687 bit in @var{mode} and call @code{chmod} again.  @xref{Permission Bits},
2688 for full details on the sticky bit.
2689 @end table
2690 @end deftypefun
2692 @comment sys/stat.h
2693 @comment BSD
2694 @deftypefun int fchmod (int @var{filedes}, mode_t @var{mode})
2695 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2696 This is like @code{chmod}, except that it changes the permissions of the
2697 currently open file given by @var{filedes}.
2699 The return value from @code{fchmod} is @code{0} on success and @code{-1}
2700 on failure.  The following @code{errno} error codes are defined for this
2701 function:
2703 @table @code
2704 @item EBADF
2705 The @var{filedes} argument is not a valid file descriptor.
2707 @item EINVAL
2708 The @var{filedes} argument corresponds to a pipe or socket, or something
2709 else that doesn't really have access permissions.
2711 @item EPERM
2712 This process does not have permission to change the access permissions
2713 of this file.  Only the file's owner (as judged by the effective user ID
2714 of the process) or a privileged user can change them.
2716 @item EROFS
2717 The file resides on a read-only file system.
2718 @end table
2719 @end deftypefun
2721 @node Testing File Access
2722 @subsection Testing Permission to Access a File
2723 @cindex testing access permission
2724 @cindex access, testing for
2725 @cindex setuid programs and file access
2727 In some situations it is desirable to allow programs to access files or
2728 devices even if this is not possible with the permissions granted to the
2729 user.  One possible solution is to set the setuid-bit of the program
2730 file.  If such a program is started the @emph{effective} user ID of the
2731 process is changed to that of the owner of the program file.  So to
2732 allow write access to files like @file{/etc/passwd}, which normally can
2733 be written only by the super-user, the modifying program will have to be
2734 owned by @code{root} and the setuid-bit must be set.
2736 But besides the files the program is intended to change the user should
2737 not be allowed to access any file to which s/he would not have access
2738 anyway.  The program therefore must explicitly check whether @emph{the
2739 user} would have the necessary access to a file, before it reads or
2740 writes the file.
2742 To do this, use the function @code{access}, which checks for access
2743 permission based on the process's @emph{real} user ID rather than the
2744 effective user ID.  (The setuid feature does not alter the real user ID,
2745 so it reflects the user who actually ran the program.)
2747 There is another way you could check this access, which is easy to
2748 describe, but very hard to use.  This is to examine the file mode bits
2749 and mimic the system's own access computation.  This method is
2750 undesirable because many systems have additional access control
2751 features; your program cannot portably mimic them, and you would not
2752 want to try to keep track of the diverse features that different systems
2753 have.  Using @code{access} is simple and automatically does whatever is
2754 appropriate for the system you are using.
2756 @code{access} is @emph{only} appropriate to use in setuid programs.
2757 A non-setuid program will always use the effective ID rather than the
2758 real ID.
2760 @pindex unistd.h
2761 The symbols in this section are declared in @file{unistd.h}.
2763 @comment unistd.h
2764 @comment POSIX.1
2765 @deftypefun int access (const char *@var{filename}, int @var{how})
2766 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2767 The @code{access} function checks to see whether the file named by
2768 @var{filename} can be accessed in the way specified by the @var{how}
2769 argument.  The @var{how} argument either can be the bitwise OR of the
2770 flags @code{R_OK}, @code{W_OK}, @code{X_OK}, or the existence test
2771 @code{F_OK}.
2773 This function uses the @emph{real} user and group IDs of the calling
2774 process, rather than the @emph{effective} IDs, to check for access
2775 permission.  As a result, if you use the function from a @code{setuid}
2776 or @code{setgid} program (@pxref{How Change Persona}), it gives
2777 information relative to the user who actually ran the program.
2779 The return value is @code{0} if the access is permitted, and @code{-1}
2780 otherwise.  (In other words, treated as a predicate function,
2781 @code{access} returns true if the requested access is @emph{denied}.)
2783 In addition to the usual file name errors (@pxref{File Name
2784 Errors}), the following @code{errno} error conditions are defined for
2785 this function:
2787 @table @code
2788 @item EACCES
2789 The access specified by @var{how} is denied.
2791 @item ENOENT
2792 The file doesn't exist.
2794 @item EROFS
2795 Write permission was requested for a file on a read-only file system.
2796 @end table
2797 @end deftypefun
2799 These macros are defined in the header file @file{unistd.h} for use
2800 as the @var{how} argument to the @code{access} function.  The values
2801 are integer constants.
2802 @pindex unistd.h
2804 @comment unistd.h
2805 @comment POSIX.1
2806 @deftypevr Macro int R_OK
2807 Flag meaning test for read permission.
2808 @end deftypevr
2810 @comment unistd.h
2811 @comment POSIX.1
2812 @deftypevr Macro int W_OK
2813 Flag meaning test for write permission.
2814 @end deftypevr
2816 @comment unistd.h
2817 @comment POSIX.1
2818 @deftypevr Macro int X_OK
2819 Flag meaning test for execute/search permission.
2820 @end deftypevr
2822 @comment unistd.h
2823 @comment POSIX.1
2824 @deftypevr Macro int F_OK
2825 Flag meaning test for existence of the file.
2826 @end deftypevr
2828 @node File Times
2829 @subsection File Times
2831 @cindex file access time
2832 @cindex file modification time
2833 @cindex file attribute modification time
2834 Each file has three time stamps associated with it:  its access time,
2835 its modification time, and its attribute modification time.  These
2836 correspond to the @code{st_atime}, @code{st_mtime}, and @code{st_ctime}
2837 members of the @code{stat} structure; see @ref{File Attributes}.
2839 All of these times are represented in calendar time format, as
2840 @code{time_t} objects.  This data type is defined in @file{time.h}.
2841 For more information about representation and manipulation of time
2842 values, see @ref{Calendar Time}.
2843 @pindex time.h
2845 Reading from a file updates its access time attribute, and writing
2846 updates its modification time.  When a file is created, all three
2847 time stamps for that file are set to the current time.  In addition, the
2848 attribute change time and modification time fields of the directory that
2849 contains the new entry are updated.
2851 Adding a new name for a file with the @code{link} function updates the
2852 attribute change time field of the file being linked, and both the
2853 attribute change time and modification time fields of the directory
2854 containing the new name.  These same fields are affected if a file name
2855 is deleted with @code{unlink}, @code{remove} or @code{rmdir}.  Renaming
2856 a file with @code{rename} affects only the attribute change time and
2857 modification time fields of the two parent directories involved, and not
2858 the times for the file being renamed.
2860 Changing the attributes of a file (for example, with @code{chmod})
2861 updates its attribute change time field.
2863 You can also change some of the time stamps of a file explicitly using
2864 the @code{utime} function---all except the attribute change time.  You
2865 need to include the header file @file{utime.h} to use this facility.
2866 @pindex utime.h
2868 @comment utime.h
2869 @comment POSIX.1
2870 @deftp {Data Type} {struct utimbuf}
2871 The @code{utimbuf} structure is used with the @code{utime} function to
2872 specify new access and modification times for a file.  It contains the
2873 following members:
2875 @table @code
2876 @item time_t actime
2877 This is the access time for the file.
2879 @item time_t modtime
2880 This is the modification time for the file.
2881 @end table
2882 @end deftp
2884 @comment utime.h
2885 @comment POSIX.1
2886 @deftypefun int utime (const char *@var{filename}, const struct utimbuf *@var{times})
2887 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2888 @c In the absence of a utime syscall, it non-atomically converts times
2889 @c to a struct timeval and calls utimes.
2890 This function is used to modify the file times associated with the file
2891 named @var{filename}.
2893 If @var{times} is a null pointer, then the access and modification times
2894 of the file are set to the current time.  Otherwise, they are set to the
2895 values from the @code{actime} and @code{modtime} members (respectively)
2896 of the @code{utimbuf} structure pointed to by @var{times}.
2898 The attribute modification time for the file is set to the current time
2899 in either case (since changing the time stamps is itself a modification
2900 of the file attributes).
2902 The @code{utime} function returns @code{0} if successful and @code{-1}
2903 on failure.  In addition to the usual file name errors
2904 (@pxref{File Name Errors}), the following @code{errno} error conditions
2905 are defined for this function:
2907 @table @code
2908 @item EACCES
2909 There is a permission problem in the case where a null pointer was
2910 passed as the @var{times} argument.  In order to update the time stamp on
2911 the file, you must either be the owner of the file, have write
2912 permission for the file, or be a privileged user.
2914 @item ENOENT
2915 The file doesn't exist.
2917 @item EPERM
2918 If the @var{times} argument is not a null pointer, you must either be
2919 the owner of the file or be a privileged user.
2921 @item EROFS
2922 The file lives on a read-only file system.
2923 @end table
2924 @end deftypefun
2926 Each of the three time stamps has a corresponding microsecond part,
2927 which extends its resolution.  These fields are called
2928 @code{st_atime_usec}, @code{st_mtime_usec}, and @code{st_ctime_usec};
2929 each has a value between 0 and 999,999, which indicates the time in
2930 microseconds.  They correspond to the @code{tv_usec} field of a
2931 @code{timeval} structure; see @ref{High-Resolution Calendar}.
2933 The @code{utimes} function is like @code{utime}, but also lets you specify
2934 the fractional part of the file times.  The prototype for this function is
2935 in the header file @file{sys/time.h}.
2936 @pindex sys/time.h
2938 @comment sys/time.h
2939 @comment BSD
2940 @deftypefun int utimes (const char *@var{filename}, const struct timeval @var{tvp}@t{[2]})
2941 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2942 @c In the absence of a utimes syscall, it non-atomically converts tvp
2943 @c to struct timespec array and issues a utimensat syscall, or to
2944 @c struct utimbuf and calls utime.
2945 This function sets the file access and modification times of the file
2946 @var{filename}.  The new file access time is specified by
2947 @code{@var{tvp}[0]}, and the new modification time by
2948 @code{@var{tvp}[1]}.  Similar to @code{utime}, if @var{tvp} is a null
2949 pointer then the access and modification times of the file are set to
2950 the current time.  This function comes from BSD.
2952 The return values and error conditions are the same as for the @code{utime}
2953 function.
2954 @end deftypefun
2956 @comment sys/time.h
2957 @comment BSD
2958 @deftypefun int lutimes (const char *@var{filename}, const struct timeval @var{tvp}@t{[2]})
2959 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2960 @c Since there's no lutimes syscall, it non-atomically converts tvp
2961 @c to struct timespec array and issues a utimensat syscall.
2962 This function is like @code{utimes}, except that it does not follow
2963 symbolic links.  If @var{filename} is the name of a symbolic link,
2964 @code{lutimes} sets the file access and modification times of the
2965 symbolic link special file itself (as seen by @code{lstat};
2966 @pxref{Symbolic Links}) while @code{utimes} sets the file access and
2967 modification times of the file the symbolic link refers to.  This
2968 function comes from FreeBSD, and is not available on all platforms (if
2969 not available, it will fail with @code{ENOSYS}).
2971 The return values and error conditions are the same as for the @code{utime}
2972 function.
2973 @end deftypefun
2975 @comment sys/time.h
2976 @comment BSD
2977 @deftypefun int futimes (int @var{fd}, const struct timeval @var{tvp}@t{[2]})
2978 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2979 @c Since there's no futimes syscall, it non-atomically converts tvp
2980 @c to struct timespec array and issues a utimensat syscall, falling back
2981 @c to utimes on a /proc/self/fd symlink.
2982 This function is like @code{utimes}, except that it takes an open file
2983 descriptor as an argument instead of a file name.  @xref{Low-Level
2984 I/O}.  This function comes from FreeBSD, and is not available on all
2985 platforms (if not available, it will fail with @code{ENOSYS}).
2987 Like @code{utimes}, @code{futimes} returns @code{0} on success and @code{-1}
2988 on failure.  The following @code{errno} error conditions are defined for
2989 @code{futimes}:
2991 @table @code
2992 @item EACCES
2993 There is a permission problem in the case where a null pointer was
2994 passed as the @var{times} argument.  In order to update the time stamp on
2995 the file, you must either be the owner of the file, have write
2996 permission for the file, or be a privileged user.
2998 @item EBADF
2999 The @var{filedes} argument is not a valid file descriptor.
3001 @item EPERM
3002 If the @var{times} argument is not a null pointer, you must either be
3003 the owner of the file or be a privileged user.
3005 @item EROFS
3006 The file lives on a read-only file system.
3007 @end table
3008 @end deftypefun
3010 @node File Size
3011 @subsection File Size
3013 Normally file sizes are maintained automatically.  A file begins with a
3014 size of @math{0} and is automatically extended when data is written past
3015 its end.  It is also possible to empty a file completely by an
3016 @code{open} or @code{fopen} call.
3018 However, sometimes it is necessary to @emph{reduce} the size of a file.
3019 This can be done with the @code{truncate} and @code{ftruncate} functions.
3020 They were introduced in BSD Unix.  @code{ftruncate} was later added to
3021 POSIX.1.
3023 Some systems allow you to extend a file (creating holes) with these
3024 functions.  This is useful when using memory-mapped I/O
3025 (@pxref{Memory-mapped I/O}), where files are not automatically extended.
3026 However, it is not portable but must be implemented if @code{mmap}
3027 allows mapping of files (i.e., @code{_POSIX_MAPPED_FILES} is defined).
3029 Using these functions on anything other than a regular file gives
3030 @emph{undefined} results.  On many systems, such a call will appear to
3031 succeed, without actually accomplishing anything.
3033 @comment unistd.h
3034 @comment X/Open
3035 @deftypefun int truncate (const char *@var{filename}, off_t @var{length})
3036 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3037 @c In the absence of a truncate syscall, we use open and ftruncate.
3039 The @code{truncate} function changes the size of @var{filename} to
3040 @var{length}.  If @var{length} is shorter than the previous length, data
3041 at the end will be lost.  The file must be writable by the user to
3042 perform this operation.
3044 If @var{length} is longer, holes will be added to the end.  However, some
3045 systems do not support this feature and will leave the file unchanged.
3047 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
3048 @code{truncate} function is in fact @code{truncate64} and the type
3049 @code{off_t} has 64 bits which makes it possible to handle files up to
3050 @twoexp{63} bytes in length.
3052 The return value is @math{0} for success, or @math{-1} for an error.  In
3053 addition to the usual file name errors, the following errors may occur:
3055 @table @code
3057 @item EACCES
3058 The file is a directory or not writable.
3060 @item EINVAL
3061 @var{length} is negative.
3063 @item EFBIG
3064 The operation would extend the file beyond the limits of the operating system.
3066 @item EIO
3067 A hardware I/O error occurred.
3069 @item EPERM
3070 The file is "append-only" or "immutable".
3072 @item EINTR
3073 The operation was interrupted by a signal.
3075 @end table
3077 @end deftypefun
3079 @comment unistd.h
3080 @comment Unix98
3081 @deftypefun int truncate64 (const char *@var{name}, off64_t @var{length})
3082 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3083 @c In the absence of a syscall, try truncate if length fits.
3084 This function is similar to the @code{truncate} function.  The
3085 difference is that the @var{length} argument is 64 bits wide even on 32
3086 bits machines, which allows the handling of files with sizes up to
3087 @twoexp{63} bytes.
3089 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
3090 32 bits machine this function is actually available under the name
3091 @code{truncate} and so transparently replaces the 32 bits interface.
3092 @end deftypefun
3094 @comment unistd.h
3095 @comment POSIX
3096 @deftypefun int ftruncate (int @var{fd}, off_t @var{length})
3097 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3099 This is like @code{truncate}, but it works on a file descriptor @var{fd}
3100 for an opened file instead of a file name to identify the object.  The
3101 file must be opened for writing to successfully carry out the operation.
3103 The POSIX standard leaves it implementation defined what happens if the
3104 specified new @var{length} of the file is bigger than the original size.
3105 The @code{ftruncate} function might simply leave the file alone and do
3106 nothing or it can increase the size to the desired size.  In this later
3107 case the extended area should be zero-filled.  So using @code{ftruncate}
3108 is no reliable way to increase the file size but if it is possible it is
3109 probably the fastest way.  The function also operates on POSIX shared
3110 memory segments if these are implemented by the system.
3112 @code{ftruncate} is especially useful in combination with @code{mmap}.
3113 Since the mapped region must have a fixed size one cannot enlarge the
3114 file by writing something beyond the last mapped page.  Instead one has
3115 to enlarge the file itself and then remap the file with the new size.
3116 The example below shows how this works.
3118 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
3119 @code{ftruncate} function is in fact @code{ftruncate64} and the type
3120 @code{off_t} has 64 bits which makes it possible to handle files up to
3121 @twoexp{63} bytes in length.
3123 The return value is @math{0} for success, or @math{-1} for an error.  The
3124 following errors may occur:
3126 @table @code
3128 @item EBADF
3129 @var{fd} does not correspond to an open file.
3131 @item EACCES
3132 @var{fd} is a directory or not open for writing.
3134 @item EINVAL
3135 @var{length} is negative.
3137 @item EFBIG
3138 The operation would extend the file beyond the limits of the operating system.
3139 @c or the open() call -- with the not-yet-discussed feature of opening
3140 @c files with extra-large offsets.
3142 @item EIO
3143 A hardware I/O error occurred.
3145 @item EPERM
3146 The file is "append-only" or "immutable".
3148 @item EINTR
3149 The operation was interrupted by a signal.
3151 @c ENOENT is also possible on Linux --- however it only occurs if the file
3152 @c descriptor has a `file' structure but no `inode' structure.  I'm not
3153 @c sure how such an fd could be created.  Perhaps it's a bug.
3155 @end table
3157 @end deftypefun
3159 @comment unistd.h
3160 @comment Unix98
3161 @deftypefun int ftruncate64 (int @var{id}, off64_t @var{length})
3162 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3163 @c In the absence of a syscall, try ftruncate if length fits.
3164 This function is similar to the @code{ftruncate} function.  The
3165 difference is that the @var{length} argument is 64 bits wide even on 32
3166 bits machines which allows the handling of files with sizes up to
3167 @twoexp{63} bytes.
3169 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
3170 32 bits machine this function is actually available under the name
3171 @code{ftruncate} and so transparently replaces the 32 bits interface.
3172 @end deftypefun
3174 As announced here is a little example of how to use @code{ftruncate} in
3175 combination with @code{mmap}:
3177 @smallexample
3178 int fd;
3179 void *start;
3180 size_t len;
3183 add (off_t at, void *block, size_t size)
3185   if (at + size > len)
3186     @{
3187       /* Resize the file and remap.  */
3188       size_t ps = sysconf (_SC_PAGESIZE);
3189       size_t ns = (at + size + ps - 1) & ~(ps - 1);
3190       void *np;
3191       if (ftruncate (fd, ns) < 0)
3192         return -1;
3193       np = mmap (NULL, ns, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
3194       if (np == MAP_FAILED)
3195         return -1;
3196       start = np;
3197       len = ns;
3198     @}
3199   memcpy ((char *) start + at, block, size);
3200   return 0;
3202 @end smallexample
3204 The function @code{add} writes a block of memory at an arbitrary
3205 position in the file.  If the current size of the file is too small it
3206 is extended.  Note that it is extended by a whole number of pages.  This
3207 is a requirement of @code{mmap}.  The program has to keep track of the
3208 real size, and when it has finished a final @code{ftruncate} call should
3209 set the real size of the file.
3211 @node Storage Allocation
3212 @subsection Storage Allocation
3213 @cindex allocating file storage
3214 @cindex file allocation
3215 @cindex storage allocating
3217 @cindex file fragmentation
3218 @cindex fragmentation of files
3219 @cindex sparse files
3220 @cindex files, sparse
3221 Most file systems support allocating large files in a non-contiguous
3222 fashion: the file is split into @emph{fragments} which are allocated
3223 sequentially, but the fragments themselves can be scattered across the
3224 disk.  File systems generally try to avoid such fragmentation because it
3225 decreases performance, but if a file gradually increases in size, there
3226 might be no other option than to fragment it.  In addition, many file
3227 systems support @emph{sparse files} with @emph{holes}: regions of null
3228 bytes for which no backing storage has been allocated by the file
3229 system.  When the holes are finally overwritten with data, fragmentation
3230 can occur as well.
3232 Explicit allocation of storage for yet-unwritten parts of the file can
3233 help the system to avoid fragmentation.  Additionally, if storage
3234 pre-allocation fails, it is possible to report the out-of-disk error
3235 early, often without filling up the entire disk.  However, due to
3236 deduplication, copy-on-write semantics, and file compression, such
3237 pre-allocation may not reliably prevent the out-of-disk-space error from
3238 occurring later.  Checking for write errors is still required, and
3239 writes to memory-mapped regions created with @code{mmap} can still
3240 result in @code{SIGBUS}.
3242 @deftypefun int posix_fallocate (int @var{fd}, off_t @var{offset}, off_t @var{length})
3243 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3244 @c If the file system does not support allocation,
3245 @c @code{posix_fallocate} has a race with file extension (if
3246 @c @var{length} is zero) or with concurrent writes of non-NUL bytes (if
3247 @c @var{length} is positive).
3249 Allocate backing store for the region of @var{length} bytes starting at
3250 byte @var{offset} in the file for the descriptor @var{fd}.  The file
3251 length is increased to @samp{@var{length} + @var{offset}} if necessary.
3253 @var{fd} must be a regular file opened for writing, or @code{EBADF} is
3254 returned.  If there is insufficient disk space to fulfill the allocation
3255 request, @code{ENOSPC} is returned.
3257 @strong{Note:} If @code{fallocate} is not available (because the file
3258 system does not support it), @code{posix_fallocate} is emulated, which
3259 has the following drawbacks:
3261 @itemize @bullet
3262 @item
3263 It is very inefficient because all file system blocks in the requested
3264 range need to be examined (even if they have been allocated before) and
3265 potentially rewritten.  In contrast, with proper @code{fallocate}
3266 support (see below), the file system can examine the internal file
3267 allocation data structures and eliminate holes directly, maybe even
3268 using unwritten extents (which are pre-allocated but uninitialized on
3269 disk).
3271 @item
3272 There is a race condition if another thread or process modifies the
3273 underlying file in the to-be-allocated area.  Non-null bytes could be
3274 overwritten with null bytes.
3276 @item
3277 If @var{fd} has been opened with the @code{O_WRONLY} flag, the function
3278 will fail with an @code{errno} value of @code{EBADF}.
3280 @item
3281 If @var{fd} has been opened with the @code{O_APPEND} flag, the function
3282 will fail with an @code{errno} value of @code{EBADF}.
3284 @item
3285 If @var{length} is zero, @code{ftruncate} is used to increase the file
3286 size as requested, without allocating file system blocks.  There is a
3287 race condition which means that @code{ftruncate} can accidentally
3288 truncate the file if it has been extended concurrently.
3289 @end itemize
3291 On Linux, if an application does not benefit from emulation or if the
3292 emulation is harmful due to its inherent race conditions, the
3293 application can use the Linux-specific @code{fallocate} function, with a
3294 zero flag argument.  For the @code{fallocate} function, @theglibc{} does
3295 not perform allocation emulation if the file system does not support
3296 allocation.  Instead, an @code{EOPNOTSUPP} is returned to the caller.
3298 @end deftypefun
3300 @deftypefun int posix_fallocate64 (int @var{fd}, off64_t @var{offset}, off64_t @var{length})
3301 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3303 This function is a variant of @code{posix_fallocate64} which accepts
3304 64-bit file offsets on all platforms.
3306 @end deftypefun
3308 @node Making Special Files
3309 @section Making Special Files
3310 @cindex creating special files
3311 @cindex special files
3313 The @code{mknod} function is the primitive for making special files,
3314 such as files that correspond to devices.  @Theglibc{} includes
3315 this function for compatibility with BSD.
3317 The prototype for @code{mknod} is declared in @file{sys/stat.h}.
3318 @pindex sys/stat.h
3320 @comment sys/stat.h
3321 @comment BSD
3322 @deftypefun int mknod (const char *@var{filename}, mode_t @var{mode}, dev_t @var{dev})
3323 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3324 @c Instead of issuing the syscall directly, we go through xmknod.
3325 @c Although the internal xmknod takes a dev_t*, that could lead to
3326 @c @mtsrace races, it's passed a pointer to mknod's dev.
3327 The @code{mknod} function makes a special file with name @var{filename}.
3328 The @var{mode} specifies the mode of the file, and may include the various
3329 special file bits, such as @code{S_IFCHR} (for a character special file)
3330 or @code{S_IFBLK} (for a block special file).  @xref{Testing File Type}.
3332 The @var{dev} argument specifies which device the special file refers to.
3333 Its exact interpretation depends on the kind of special file being created.
3335 The return value is @code{0} on success and @code{-1} on error.  In addition
3336 to the usual file name errors (@pxref{File Name Errors}), the
3337 following @code{errno} error conditions are defined for this function:
3339 @table @code
3340 @item EPERM
3341 The calling process is not privileged.  Only the superuser can create
3342 special files.
3344 @item ENOSPC
3345 The directory or file system that would contain the new file is full
3346 and cannot be extended.
3348 @item EROFS
3349 The directory containing the new file can't be modified because it's on
3350 a read-only file system.
3352 @item EEXIST
3353 There is already a file named @var{filename}.  If you want to replace
3354 this file, you must remove the old file explicitly first.
3355 @end table
3356 @end deftypefun
3358 @node Temporary Files
3359 @section Temporary Files
3361 If you need to use a temporary file in your program, you can use the
3362 @code{tmpfile} function to open it.  Or you can use the @code{tmpnam}
3363 (better: @code{tmpnam_r}) function to provide a name for a temporary
3364 file and then you can open it in the usual way with @code{fopen}.
3366 The @code{tempnam} function is like @code{tmpnam} but lets you choose
3367 what directory temporary files will go in, and something about what
3368 their file names will look like.  Important for multi-threaded programs
3369 is that @code{tempnam} is reentrant, while @code{tmpnam} is not since it
3370 returns a pointer to a static buffer.
3372 These facilities are declared in the header file @file{stdio.h}.
3373 @pindex stdio.h
3375 @comment stdio.h
3376 @comment ISO
3377 @deftypefun {FILE *} tmpfile (void)
3378 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @acsfd{} @aculock{}}}
3379 @c The unsafety issues are those of fdopen, plus @acsfd because of the
3380 @c open.
3381 @c __path_search (internal buf, !dir, const pfx, !try_tmpdir) ok
3382 @c  libc_secure_genenv only if try_tmpdir
3383 @c  xstat64, strlen, strcmp, sprintf
3384 @c __gen_tempname (internal tmpl, __GT_FILE) ok
3385 @c  strlen, memcmp, getpid, open/mkdir/lxstat64 ok
3386 @c  HP_TIMING_NOW if available ok
3387 @c  gettimeofday (!tz) first time, or every time if no HP_TIMING_NOW ok
3388 @c  static value is used and modified without synchronization ok
3389 @c   but the use is as a source of non-cryptographic randomness
3390 @c   with retries in case of collision, so it should be safe
3391 @c unlink, fdopen
3392 This function creates a temporary binary file for update mode, as if by
3393 calling @code{fopen} with mode @code{"wb+"}.  The file is deleted
3394 automatically when it is closed or when the program terminates.  (On
3395 some other @w{ISO C} systems the file may fail to be deleted if the program
3396 terminates abnormally).
3398 This function is reentrant.
3400 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
3401 32-bit system this function is in fact @code{tmpfile64}, i.e., the LFS
3402 interface transparently replaces the old interface.
3403 @end deftypefun
3405 @comment stdio.h
3406 @comment Unix98
3407 @deftypefun {FILE *} tmpfile64 (void)
3408 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @acsfd{} @aculock{}}}
3409 This function is similar to @code{tmpfile}, but the stream it returns a
3410 pointer to was opened using @code{tmpfile64}.  Therefore this stream can
3411 be used for files larger than @twoexp{31} bytes on 32-bit machines.
3413 Please note that the return type is still @code{FILE *}.  There is no
3414 special @code{FILE} type for the LFS interface.
3416 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
3417 bits machine this function is available under the name @code{tmpfile}
3418 and so transparently replaces the old interface.
3419 @end deftypefun
3421 @comment stdio.h
3422 @comment ISO
3423 @deftypefun {char *} tmpnam (char *@var{result})
3424 @safety{@prelim{}@mtunsafe{@mtasurace{:tmpnam/!result}}@asunsafe{}@acsafe{}}
3425 @c The passed-in buffer should not be modified concurrently with the
3426 @c call.
3427 @c __path_search (static or passed-in buf, !dir, !pfx, !try_tmpdir) ok
3428 @c __gen_tempname (internal tmpl, __GT_NOCREATE) ok
3429 This function constructs and returns a valid file name that does not
3430 refer to any existing file.  If the @var{result} argument is a null
3431 pointer, the return value is a pointer to an internal static string,
3432 which might be modified by subsequent calls and therefore makes this
3433 function non-reentrant.  Otherwise, the @var{result} argument should be
3434 a pointer to an array of at least @code{L_tmpnam} characters, and the
3435 result is written into that array.
3437 It is possible for @code{tmpnam} to fail if you call it too many times
3438 without removing previously-created files.  This is because the limited
3439 length of the temporary file names gives room for only a finite number
3440 of different names.  If @code{tmpnam} fails it returns a null pointer.
3442 @strong{Warning:} Between the time the pathname is constructed and the
3443 file is created another process might have created a file with the same
3444 name using @code{tmpnam}, leading to a possible security hole.  The
3445 implementation generates names which can hardly be predicted, but when
3446 opening the file you should use the @code{O_EXCL} flag.  Using
3447 @code{tmpfile} or @code{mkstemp} is a safe way to avoid this problem.
3448 @end deftypefun
3450 @comment stdio.h
3451 @comment GNU
3452 @deftypefun {char *} tmpnam_r (char *@var{result})
3453 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3454 This function is nearly identical to the @code{tmpnam} function, except
3455 that if @var{result} is a null pointer it returns a null pointer.
3457 This guarantees reentrancy because the non-reentrant situation of
3458 @code{tmpnam} cannot happen here.
3460 @strong{Warning}: This function has the same security problems as
3461 @code{tmpnam}.
3462 @end deftypefun
3464 @comment stdio.h
3465 @comment ISO
3466 @deftypevr Macro int L_tmpnam
3467 The value of this macro is an integer constant expression that
3468 represents the minimum size of a string large enough to hold a file name
3469 generated by the @code{tmpnam} function.
3470 @end deftypevr
3472 @comment stdio.h
3473 @comment ISO
3474 @deftypevr Macro int TMP_MAX
3475 The macro @code{TMP_MAX} is a lower bound for how many temporary names
3476 you can create with @code{tmpnam}.  You can rely on being able to call
3477 @code{tmpnam} at least this many times before it might fail saying you
3478 have made too many temporary file names.
3480 With @theglibc{}, you can create a very large number of temporary
3481 file names.  If you actually created the files, you would probably run
3482 out of disk space before you ran out of names.  Some other systems have
3483 a fixed, small limit on the number of temporary files.  The limit is
3484 never less than @code{25}.
3485 @end deftypevr
3487 @comment stdio.h
3488 @comment SVID
3489 @deftypefun {char *} tempnam (const char *@var{dir}, const char *@var{prefix})
3490 @safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
3491 @c There's no way (short of being setuid) to avoid getenv("TMPDIR"),
3492 @c even with a non-NULL dir.
3494 @c __path_search (internal buf, dir, pfx, try_tmpdir) unsafe getenv
3495 @c __gen_tempname (internal tmpl, __GT_NOCREATE) ok
3496 @c strdup
3497 This function generates a unique temporary file name.  If @var{prefix}
3498 is not a null pointer, up to five characters of this string are used as
3499 a prefix for the file name.  The return value is a string newly
3500 allocated with @code{malloc}, so you should release its storage with
3501 @code{free} when it is no longer needed.
3503 Because the string is dynamically allocated this function is reentrant.
3505 The directory prefix for the temporary file name is determined by
3506 testing each of the following in sequence.  The directory must exist and
3507 be writable.
3509 @itemize @bullet
3510 @item
3511 The environment variable @code{TMPDIR}, if it is defined.  For security
3512 reasons this only happens if the program is not SUID or SGID enabled.
3514 @item
3515 The @var{dir} argument, if it is not a null pointer.
3517 @item
3518 The value of the @code{P_tmpdir} macro.
3520 @item
3521 The directory @file{/tmp}.
3522 @end itemize
3524 This function is defined for SVID compatibility.
3526 @strong{Warning:} Between the time the pathname is constructed and the
3527 file is created another process might have created a file with the same
3528 name using @code{tempnam}, leading to a possible security hole.  The
3529 implementation generates names which can hardly be predicted, but when
3530 opening the file you should use the @code{O_EXCL} flag.  Using
3531 @code{tmpfile} or @code{mkstemp} is a safe way to avoid this problem.
3532 @end deftypefun
3533 @cindex TMPDIR environment variable
3535 @comment stdio.h
3536 @comment SVID
3537 @c !!! are we putting SVID/GNU/POSIX.1/BSD in here or not??
3538 @deftypevr {SVID Macro} {char *} P_tmpdir
3539 This macro is the name of the default directory for temporary files.
3540 @end deftypevr
3542 Older Unix systems did not have the functions just described.  Instead
3543 they used @code{mktemp} and @code{mkstemp}.  Both of these functions
3544 work by modifying a file name template string you pass.  The last six
3545 characters of this string must be @samp{XXXXXX}.  These six @samp{X}s
3546 are replaced with six characters which make the whole string a unique
3547 file name.  Usually the template string is something like
3548 @samp{/tmp/@var{prefix}XXXXXX}, and each program uses a unique @var{prefix}.
3550 @strong{NB:} Because @code{mktemp} and @code{mkstemp} modify the
3551 template string, you @emph{must not} pass string constants to them.
3552 String constants are normally in read-only storage, so your program
3553 would crash when @code{mktemp} or @code{mkstemp} tried to modify the
3554 string.  These functions are declared in the header file @file{stdlib.h}.
3555 @pindex stdlib.h
3557 @comment stdlib.h
3558 @comment Unix
3559 @deftypefun {char *} mktemp (char *@var{template})
3560 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3561 @c __gen_tempname (caller tmpl, __GT_NOCREATE) ok
3562 The @code{mktemp} function generates a unique file name by modifying
3563 @var{template} as described above.  If successful, it returns
3564 @var{template} as modified.  If @code{mktemp} cannot find a unique file
3565 name, it makes @var{template} an empty string and returns that.  If
3566 @var{template} does not end with @samp{XXXXXX}, @code{mktemp} returns a
3567 null pointer.
3569 @strong{Warning:} Between the time the pathname is constructed and the
3570 file is created another process might have created a file with the same
3571 name using @code{mktemp}, leading to a possible security hole.  The
3572 implementation generates names which can hardly be predicted, but when
3573 opening the file you should use the @code{O_EXCL} flag.  Using
3574 @code{mkstemp} is a safe way to avoid this problem.
3575 @end deftypefun
3577 @comment stdlib.h
3578 @comment BSD
3579 @deftypefun int mkstemp (char *@var{template})
3580 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
3581 @c __gen_tempname (caller tmpl, __GT_FILE) ok
3582 The @code{mkstemp} function generates a unique file name just as
3583 @code{mktemp} does, but it also opens the file for you with @code{open}
3584 (@pxref{Opening and Closing Files}).  If successful, it modifies
3585 @var{template} in place and returns a file descriptor for that file open
3586 for reading and writing.  If @code{mkstemp} cannot create a
3587 uniquely-named file, it returns @code{-1}.  If @var{template} does not
3588 end with @samp{XXXXXX}, @code{mkstemp} returns @code{-1} and does not
3589 modify @var{template}.
3591 The file is opened using mode @code{0600}.  If the file is meant to be
3592 used by other users this mode must be changed explicitly.
3593 @end deftypefun
3595 Unlike @code{mktemp}, @code{mkstemp} is actually guaranteed to create a
3596 unique file that cannot possibly clash with any other program trying to
3597 create a temporary file.  This is because it works by calling
3598 @code{open} with the @code{O_EXCL} flag, which says you want to create a
3599 new file and get an error if the file already exists.
3601 @comment stdlib.h
3602 @comment BSD
3603 @deftypefun {char *} mkdtemp (char *@var{template})
3604 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3605 @c __gen_tempname (caller tmpl, __GT_DIR) ok
3606 The @code{mkdtemp} function creates a directory with a unique name.  If
3607 it succeeds, it overwrites @var{template} with the name of the
3608 directory, and returns @var{template}.  As with @code{mktemp} and
3609 @code{mkstemp}, @var{template} should be a string ending with
3610 @samp{XXXXXX}.
3612 If @code{mkdtemp} cannot create an uniquely named directory, it returns
3613 @code{NULL} and sets @var{errno} appropriately.  If @var{template} does
3614 not end with @samp{XXXXXX}, @code{mkdtemp} returns @code{NULL} and does
3615 not modify @var{template}.  @var{errno} will be set to @code{EINVAL} in
3616 this case.
3618 The directory is created using mode @code{0700}.
3619 @end deftypefun
3621 The directory created by @code{mkdtemp} cannot clash with temporary
3622 files or directories created by other users.  This is because directory
3623 creation always works like @code{open} with @code{O_EXCL}.
3624 @xref{Creating Directories}.
3626 The @code{mkdtemp} function comes from OpenBSD.
3628 @c FIXME these are undocumented:
3629 @c faccessat
3630 @c fchmodat
3631 @c fchownat
3632 @c futimesat
3633 @c fstatat (there's a commented-out safety assessment for this one)
3634 @c linkat
3635 @c mkdirat
3636 @c mkfifoat
3637 @c name_to_handle_at
3638 @c openat
3639 @c open_by_handle_at
3640 @c readlinkat
3641 @c renameat
3642 @c scandirat
3643 @c symlinkat
3644 @c unlinkat
3645 @c utimensat
3646 @c mknodat