Use common bits/shm.h for more architectures.
[glibc.git] / manual / filesys.texi
blobccda36cf84339ed728803cc4154259a40490108c
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 @deftypefun {char *} getcwd (char *@var{buffer}, size_t @var{size})
59 @standards{POSIX.1, unistd.h}
60 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
61 @c If buffer is NULL, this function calls malloc and realloc, and, in
62 @c case of error, free.  Linux offers a getcwd syscall that we use on
63 @c GNU/Linux systems, but it may fail if the pathname is too long.  As a
64 @c fallback, and on other systems, the generic implementation opens each
65 @c parent directory with opendir, which allocates memory for the
66 @c directory stream with malloc.  If a fstatat64 syscall is not
67 @c available, very deep directory trees may also have to malloc to build
68 @c longer sequences of ../../../... than those supported by a global
69 @c const read-only string.
71 @c linux/__getcwd
72 @c  posix/__getcwd
73 @c   malloc/realloc/free if buffer is NULL, or if dir is too deep
74 @c   lstat64 -> see its own entry
75 @c   fstatat64
76 @c     direct syscall if possible, alloca+snprintf+*stat64 otherwise
77 @c   openat64_not_cancel_3, close_not_cancel_no_status
78 @c   __fdopendir, __opendir, __readdir, rewinddir
79 The @code{getcwd} function returns an absolute file name representing
80 the current working directory, storing it in the character array
81 @var{buffer} that you provide.  The @var{size} argument is how you tell
82 the system the allocation size of @var{buffer}.
84 The @glibcadj{} version of this function also permits you to specify a
85 null pointer for the @var{buffer} argument.  Then @code{getcwd}
86 allocates a buffer automatically, as with @code{malloc}
87 (@pxref{Unconstrained Allocation}).  If the @var{size} is greater than
88 zero, then the buffer is that large; otherwise, the buffer is as large
89 as necessary to hold the result.
91 The return value is @var{buffer} on success and a null pointer on failure.
92 The following @code{errno} error conditions are defined for this function:
94 @table @code
95 @item EINVAL
96 The @var{size} argument is zero and @var{buffer} is not a null pointer.
98 @item ERANGE
99 The @var{size} argument is less than the length of the working directory
100 name.  You need to allocate a bigger array and try again.
102 @item EACCES
103 Permission to read or search a component of the file name was denied.
104 @end table
105 @end deftypefun
107 You could implement the behavior of GNU's @w{@code{getcwd (NULL, 0)}}
108 using only the standard behavior of @code{getcwd}:
110 @smallexample
111 char *
112 gnu_getcwd ()
114   size_t size = 100;
116   while (1)
117     @{
118       char *buffer = (char *) xmalloc (size);
119       if (getcwd (buffer, size) == buffer)
120         return buffer;
121       free (buffer);
122       if (errno != ERANGE)
123         return 0;
124       size *= 2;
125     @}
127 @end smallexample
129 @noindent
130 @xref{Malloc Examples}, for information about @code{xmalloc}, which is
131 not a library function but is a customary name used in most GNU
132 software.
134 @deftypefn {Deprecated Function} {char *} getwd (char *@var{buffer})
135 @standards{BSD, unistd.h}
136 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @ascuintl{}}@acunsafe{@acsmem{} @acsfd{}}}
137 @c Besides the getcwd safety issues, it calls strerror_r on error, which
138 @c brings in all of the i18n issues.
139 This is similar to @code{getcwd}, but has no way to specify the size of
140 the buffer.  @Theglibc{} provides @code{getwd} only
141 for backwards compatibility with BSD.
143 The @var{buffer} argument should be a pointer to an array at least
144 @code{PATH_MAX} bytes long (@pxref{Limits for Files}).  On @gnuhurdsystems{}
145 there is no limit to the size of a file name, so this is not
146 necessarily enough space to contain the directory name.  That is why
147 this function is deprecated.
148 @end deftypefn
150 @vindex PWD
151 @deftypefun {char *} get_current_dir_name (void)
152 @standards{GNU, unistd.h}
153 @safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
154 @c Besides getcwd, which this function calls as a fallback, it calls
155 @c getenv, with the potential thread-safety issues that brings about.
156 The @code{get_current_dir_name} function is basically equivalent to
157 @w{@code{getcwd (NULL, 0)}}, except the value of the @env{PWD}
158 environment variable is first examined, and if it does in fact
159 correspond to the current directory, that value is returned.  This is
160 a subtle difference which is visible if the path described by the
161 value in @env{PWD} is using one or more symbolic links, in which case
162 the value returned by @code{getcwd} would resolve the symbolic links
163 and therefore yield a different result.
165 This function is a GNU extension.
166 @end deftypefun
168 @deftypefun int chdir (const char *@var{filename})
169 @standards{POSIX.1, unistd.h}
170 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
171 This function is used to set the process's working directory to
172 @var{filename}.
174 The normal, successful return value from @code{chdir} is @code{0}.  A
175 value of @code{-1} is returned to indicate an error.  The @code{errno}
176 error conditions defined for this function are the usual file name
177 syntax errors (@pxref{File Name Errors}), plus @code{ENOTDIR} if the
178 file @var{filename} is not a directory.
179 @end deftypefun
181 @deftypefun int fchdir (int @var{filedes})
182 @standards{XPG, unistd.h}
183 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
184 This function is used to set the process's working directory to
185 directory associated with the file descriptor @var{filedes}.
187 The normal, successful return value from @code{fchdir} is @code{0}.  A
188 value of @code{-1} is returned to indicate an error.  The following
189 @code{errno} error conditions are defined for this function:
191 @table @code
192 @item EACCES
193 Read permission is denied for the directory named by @code{dirname}.
195 @item EBADF
196 The @var{filedes} argument is not a valid file descriptor.
198 @item ENOTDIR
199 The file descriptor @var{filedes} is not associated with a directory.
201 @item EINTR
202 The function call was interrupt by a signal.
204 @item EIO
205 An I/O error occurred.
206 @end table
207 @end deftypefun
210 @node Accessing Directories
211 @section Accessing Directories
212 @cindex accessing directories
213 @cindex reading from a directory
214 @cindex directories, accessing
216 The facilities described in this section let you read the contents of a
217 directory file.  This is useful if you want your program to list all the
218 files in a directory, perhaps as part of a menu.
220 @cindex directory stream
221 The @code{opendir} function opens a @dfn{directory stream} whose
222 elements are directory entries.  Alternatively @code{fdopendir} can be
223 used which can have advantages if the program needs to have more
224 control over the way the directory is opened for reading.  This
225 allows, for instance, to pass the @code{O_NOATIME} flag to
226 @code{open}.
228 You use the @code{readdir} function on the directory stream to
229 retrieve these entries, represented as @w{@code{struct dirent}}
230 objects.  The name of the file for each entry is stored in the
231 @code{d_name} member of this structure.  There are obvious parallels
232 here to the stream facilities for ordinary files, described in
233 @ref{I/O on Streams}.
235 @menu
236 * Directory Entries::           Format of one directory entry.
237 * Opening a Directory::         How to open a directory stream.
238 * Reading/Closing Directory::   How to read directory entries from the stream.
239 * Simple Directory Lister::     A very simple directory listing program.
240 * Random Access Directory::     Rereading part of the directory
241                                  already read with the same stream.
242 * Scanning Directory Content::  Get entries for user selected subset of
243                                  contents in given directory.
244 * Simple Directory Lister Mark II::  Revised version of the program.
245 @end menu
247 @node Directory Entries
248 @subsection Format of a Directory Entry
250 @pindex dirent.h
251 This section describes what you find in a single directory entry, as you
252 might obtain it from a directory stream.  All the symbols are declared
253 in the header file @file{dirent.h}.
255 @deftp {Data Type} {struct dirent}
256 @standards{POSIX.1, dirent.h}
257 This is a structure type used to return information about directory
258 entries.  It contains the following fields:
260 @table @code
261 @item char d_name[]
262 This is the null-terminated file name component.  This is the only
263 field you can count on in all POSIX systems.
265 @item ino_t d_fileno
266 This is the file serial number.  For BSD compatibility, you can also
267 refer to this member as @code{d_ino}.  On @gnulinuxhurdsystems{} and most POSIX
268 systems, for most files this the same as the @code{st_ino} member that
269 @code{stat} will return for the file.  @xref{File Attributes}.
271 @item unsigned char d_namlen
272 This is the length of the file name, not including the terminating
273 null character.  Its type is @code{unsigned char} because that is the
274 integer type of the appropriate size.  This member is a BSD extension.
275 The symbol @code{_DIRENT_HAVE_D_NAMLEN} is defined if this member is
276 available.
278 @item unsigned char d_type
279 This is the type of the file, possibly unknown.  The following constants
280 are defined for its value:
282 @vtable @code
283 @item DT_UNKNOWN
284 The type is unknown.  Only some filesystems have full support to
285 return the type of the file, others might always return this value.
287 @item DT_REG
288 A regular file.
290 @item DT_DIR
291 A directory.
293 @item DT_FIFO
294 A named pipe, or FIFO.  @xref{FIFO Special Files}.
296 @item DT_SOCK
297 A local-domain socket.  @c !!! @xref{Local Domain}.
299 @item DT_CHR
300 A character device.
302 @item DT_BLK
303 A block device.
305 @item DT_LNK
306 A symbolic link.
307 @end vtable
309 This member is a BSD extension.  The symbol @code{_DIRENT_HAVE_D_TYPE}
310 is defined if this member is available.  On systems where it is used, it
311 corresponds to the file type bits in the @code{st_mode} member of
312 @code{struct stat}.  If the value cannot be determined the member
313 value is DT_UNKNOWN.  These two macros convert between @code{d_type}
314 values and @code{st_mode} values:
316 @deftypefun int IFTODT (mode_t @var{mode})
317 @standards{BSD, dirent.h}
318 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
319 This returns the @code{d_type} value corresponding to @var{mode}.
320 @end deftypefun
322 @deftypefun mode_t DTTOIF (int @var{dtype})
323 @standards{BSD, dirent.h}
324 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
325 This returns the @code{st_mode} value corresponding to @var{dtype}.
326 @end deftypefun
327 @end table
329 This structure may contain additional members in the future.  Their
330 availability is always announced in the compilation environment by a
331 macro named @code{_DIRENT_HAVE_D_@var{xxx}} where @var{xxx} is replaced
332 by the name of the new member.  For instance, the member @code{d_reclen}
333 available on some systems is announced through the macro
334 @code{_DIRENT_HAVE_D_RECLEN}.
336 When a file has multiple names, each name has its own directory entry.
337 The only way you can tell that the directory entries belong to a
338 single file is that they have the same value for the @code{d_fileno}
339 field.
341 File attributes such as size, modification times etc., are part of the
342 file itself, not of any particular directory entry.  @xref{File
343 Attributes}.
344 @end deftp
346 @node Opening a Directory
347 @subsection Opening a Directory Stream
349 @pindex dirent.h
350 This section describes how to open a directory stream.  All the symbols
351 are declared in the header file @file{dirent.h}.
353 @deftp {Data Type} DIR
354 @standards{POSIX.1, dirent.h}
355 The @code{DIR} data type represents a directory stream.
356 @end deftp
358 You shouldn't ever allocate objects of the @code{struct dirent} or
359 @code{DIR} data types, since the directory access functions do that for
360 you.  Instead, you refer to these objects using the pointers returned by
361 the following functions.
363 @deftypefun {DIR *} opendir (const char *@var{dirname})
364 @standards{POSIX.1, dirent.h}
365 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
366 @c Besides the safe syscall, we have to allocate the DIR object with
367 @c __alloc_dir, that calls malloc.
368 The @code{opendir} function opens and returns a directory stream for
369 reading the directory whose file name is @var{dirname}.  The stream has
370 type @code{DIR *}.
372 If unsuccessful, @code{opendir} returns a null pointer.  In addition to
373 the usual file name errors (@pxref{File Name Errors}), the
374 following @code{errno} error conditions are defined for this function:
376 @table @code
377 @item EACCES
378 Read permission is denied for the directory named by @code{dirname}.
380 @item EMFILE
381 The process has too many files open.
383 @item ENFILE
384 The entire system, or perhaps the file system which contains the
385 directory, cannot support any additional open files at the moment.
386 (This problem cannot happen on @gnuhurdsystems{}.)
388 @item ENOMEM
389 Not enough memory available.
390 @end table
392 The @code{DIR} type is typically implemented using a file descriptor,
393 and the @code{opendir} function in terms of the @code{open} function.
394 @xref{Low-Level I/O}.  Directory streams and the underlying
395 file descriptors are closed on @code{exec} (@pxref{Executing a File}).
396 @end deftypefun
398 The directory which is opened for reading by @code{opendir} is
399 identified by the name.  In some situations this is not sufficient.
400 Or the way @code{opendir} implicitly creates a file descriptor for the
401 directory is not the way a program might want it.  In these cases an
402 alternative interface can be used.
404 @deftypefun {DIR *} fdopendir (int @var{fd})
405 @standards{GNU, dirent.h}
406 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
407 @c The DIR object is allocated with __alloc_dir, that calls malloc.
408 The @code{fdopendir} function works just like @code{opendir} but
409 instead of taking a file name and opening a file descriptor for the
410 directory the caller is required to provide a file descriptor.  This
411 file descriptor is then used in subsequent uses of the returned
412 directory stream object.
414 The caller must make sure the file descriptor is associated with a
415 directory and it allows reading.
417 If the @code{fdopendir} call returns successfully the file descriptor
418 is now under the control of the system.  It can be used in the same
419 way the descriptor implicitly created by @code{opendir} can be used
420 but the program must not close the descriptor.
422 In case the function is unsuccessful it returns a null pointer and the
423 file descriptor remains to be usable by the program.  The following
424 @code{errno} error conditions are defined for this function:
426 @table @code
427 @item EBADF
428 The file descriptor is not valid.
430 @item ENOTDIR
431 The file descriptor is not associated with a directory.
433 @item EINVAL
434 The descriptor does not allow reading the directory content.
436 @item ENOMEM
437 Not enough memory available.
438 @end table
439 @end deftypefun
441 In some situations it can be desirable to get hold of the file
442 descriptor which is created by the @code{opendir} call.  For instance,
443 to switch the current working directory to the directory just read the
444 @code{fchdir} function could be used.  Historically the @code{DIR} type
445 was exposed and programs could access the fields.  This does not happen
446 in @theglibc{}.  Instead a separate function is provided to allow
447 access.
449 @deftypefun int dirfd (DIR *@var{dirstream})
450 @standards{GNU, dirent.h}
451 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
452 The function @code{dirfd} returns the file descriptor associated with
453 the directory stream @var{dirstream}.  This descriptor can be used until
454 the directory is closed with @code{closedir}.  If the directory stream
455 implementation is not using file descriptors the return value is
456 @code{-1}.
457 @end deftypefun
459 @node Reading/Closing Directory
460 @subsection Reading and Closing a Directory Stream
462 @pindex dirent.h
463 This section describes how to read directory entries from a directory
464 stream, and how to close the stream when you are done with it.  All the
465 symbols are declared in the header file @file{dirent.h}.
467 @deftypefun {struct dirent *} readdir (DIR *@var{dirstream})
468 @standards{POSIX.1, dirent.h}
469 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
470 @c This function holds dirstream's non-recursive lock, which brings
471 @c about the usual issues with locks and async signals and cancellation,
472 @c but the lock taking is not enough to make the returned value safe to
473 @c use, since it points to a stream's internal buffer that can be
474 @c overwritten by subsequent calls or even released by closedir.
475 This function reads the next entry from the directory.  It normally
476 returns a pointer to a structure containing information about the
477 file.  This structure is associated with the @var{dirstream} handle
478 and can be rewritten by a subsequent call.
480 @strong{Portability Note:} On some systems @code{readdir} may not
481 return entries for @file{.} and @file{..}, even though these are always
482 valid file names in any directory.  @xref{File Name Resolution}.
484 If there are no more entries in the directory or an error is detected,
485 @code{readdir} returns a null pointer.  The following @code{errno} error
486 conditions are defined for this function:
488 @table @code
489 @item EBADF
490 The @var{dirstream} argument is not valid.
491 @end table
493 To distinguish between an end-of-directory condition or an error, you
494 must set @code{errno} to zero before calling @code{readdir}.  To avoid
495 entering an infinite loop, you should stop reading from the directory
496 after the first error.
498 @strong{Caution:} The pointer returned by @code{readdir} points to
499 a buffer within the @code{DIR} object.  The data in that buffer will
500 be overwritten by the next call to @code{readdir}.  You must take care,
501 for instance, to copy the @code{d_name} string if you need it later.
503 Because of this, it is not safe to share a @code{DIR} object among
504 multiple threads, unless you use your own locking to ensure that
505 no thread calls @code{readdir} while another thread is still using the
506 data from the previous call.  In @theglibc{}, it is safe to call
507 @code{readdir} from multiple threads as long as each thread uses
508 its own @code{DIR} object.  POSIX.1-2008 does not require this to
509 be safe, but we are not aware of any operating systems where it
510 does not work.
512 @code{readdir_r} allows you to provide your own buffer for the
513 @code{struct dirent}, but it is less portable than @code{readdir}, and
514 has problems with very long filenames (see below).  We recommend
515 you use @code{readdir}, but do not share @code{DIR} objects.
516 @end deftypefun
518 @deftypefun int readdir_r (DIR *@var{dirstream}, struct dirent *@var{entry}, struct dirent **@var{result})
519 @standards{GNU, dirent.h}
520 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
521 This function is a version of @code{readdir} which performs internal
522 locking.  Like @code{readdir} it returns the next entry from the
523 directory.  To prevent conflicts between simultaneously running
524 threads the result is stored inside the @var{entry} object.
526 @strong{Portability Note:} @code{readdir_r} is deprecated.  It is
527 recommended to use @code{readdir} instead of @code{readdir_r} for the
528 following reasons:
530 @itemize @bullet
531 @item
532 On systems which do not define @code{NAME_MAX}, it may not be possible
533 to use @code{readdir_r} safely because the caller does not specify the
534 length of the buffer for the directory entry.
536 @item
537 On some systems, @code{readdir_r} cannot read directory entries with
538 very long names.  If such a name is encountered, @theglibc{}
539 implementation of @code{readdir_r} returns with an error code of
540 @code{ENAMETOOLONG} after the final directory entry has been read.  On
541 other systems, @code{readdir_r} may return successfully, but the
542 @code{d_name} member may not be NUL-terminated or may be truncated.
544 @item
545 POSIX-1.2008 does not guarantee that @code{readdir} is thread-safe,
546 even when access to the same @var{dirstream} is serialized.  But in
547 current implementations (including @theglibc{}), it is safe to call
548 @code{readdir} concurrently on different @var{dirstream}s, so there is
549 no need to use @code{readdir_r} in most multi-threaded programs.  In
550 the rare case that multiple threads need to read from the same
551 @var{dirstream}, it is still better to use @code{readdir} and external
552 synchronization.
554 @item
555 It is expected that future versions of POSIX will obsolete
556 @code{readdir_r} and mandate the level of thread safety for
557 @code{readdir} which is provided by @theglibc{} and other
558 implementations today.
559 @end itemize
561 Normally @code{readdir_r} returns zero and sets @code{*@var{result}}
562 to @var{entry}.  If there are no more entries in the directory or an
563 error is detected, @code{readdir_r} sets @code{*@var{result}} to a
564 null pointer and returns a nonzero error code, also stored in
565 @code{errno}, as described for @code{readdir}.
567 It is also important to look at the definition of the @code{struct
568 dirent} type.  Simply passing a pointer to an object of this type for
569 the second parameter of @code{readdir_r} might not be enough.  Some
570 systems don't define the @code{d_name} element sufficiently long.  In
571 this case the user has to provide additional space.  There must be room
572 for at least @code{NAME_MAX + 1} characters in the @code{d_name} array.
573 Code to call @code{readdir_r} could look like this:
575 @smallexample
576   union
577   @{
578     struct dirent d;
579     char b[offsetof (struct dirent, d_name) + NAME_MAX + 1];
580   @} u;
582   if (readdir_r (dir, &u.d, &res) == 0)
583     @dots{}
584 @end smallexample
585 @end deftypefun
587 To support large filesystems on 32-bit machines there are LFS variants
588 of the last two functions.
590 @deftypefun {struct dirent64 *} readdir64 (DIR *@var{dirstream})
591 @standards{LFS, dirent.h}
592 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
593 The @code{readdir64} function is just like the @code{readdir} function
594 except that it returns a pointer to a record of type @code{struct
595 dirent64}.  Some of the members of this data type (notably @code{d_ino})
596 might have a different size to allow large filesystems.
598 In all other aspects this function is equivalent to @code{readdir}.
599 @end deftypefun
601 @deftypefun int readdir64_r (DIR *@var{dirstream}, struct dirent64 *@var{entry}, struct dirent64 **@var{result})
602 @standards{LFS, dirent.h}
603 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
604 The deprecated @code{readdir64_r} function is equivalent to the
605 @code{readdir_r} function except that it takes parameters of base type
606 @code{struct dirent64} instead of @code{struct dirent} in the second and
607 third position.  The same precautions mentioned in the documentation of
608 @code{readdir_r} also apply here.
609 @end deftypefun
611 @deftypefun int closedir (DIR *@var{dirstream})
612 @standards{POSIX.1, dirent.h}
613 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{/hurd}}@acunsafe{@acsmem{} @acsfd{} @aculock{/hurd}}}
614 @c No synchronization in the posix implementation, only in the hurd
615 @c one.  This is regarded as safe because it is undefined behavior if
616 @c other threads could still be using the dir stream while it's closed.
617 This function closes the directory stream @var{dirstream}.  It returns
618 @code{0} on success and @code{-1} on failure.
620 The following @code{errno} error conditions are defined for this
621 function:
623 @table @code
624 @item EBADF
625 The @var{dirstream} argument is not valid.
626 @end table
627 @end deftypefun
629 @node Simple Directory Lister
630 @subsection Simple Program to List a Directory
632 Here's a simple program that prints the names of the files in
633 the current working directory:
635 @smallexample
636 @include dir.c.texi
637 @end smallexample
639 The order in which files appear in a directory tends to be fairly
640 random.  A more useful program would sort the entries (perhaps by
641 alphabetizing them) before printing them; see
642 @ref{Scanning Directory Content}, and @ref{Array Sort Function}.
645 @node Random Access Directory
646 @subsection Random Access in a Directory Stream
648 @pindex dirent.h
649 This section describes how to reread parts of a directory that you have
650 already read from an open directory stream.  All the symbols are
651 declared in the header file @file{dirent.h}.
653 @deftypefun void rewinddir (DIR *@var{dirstream})
654 @standards{POSIX.1, dirent.h}
655 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
656 The @code{rewinddir} function is used to reinitialize the directory
657 stream @var{dirstream}, so that if you call @code{readdir} it
658 returns information about the first entry in the directory again.  This
659 function also notices if files have been added or removed to the
660 directory since it was opened with @code{opendir}.  (Entries for these
661 files might or might not be returned by @code{readdir} if they were
662 added or removed since you last called @code{opendir} or
663 @code{rewinddir}.)
664 @end deftypefun
666 @deftypefun {long int} telldir (DIR *@var{dirstream})
667 @standards{BSD, dirent.h}
668 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{/bsd} @asulock{/bsd}}@acunsafe{@acsmem{/bsd} @aculock{/bsd}}}
669 @c The implementation is safe on most platforms, but on BSD it uses
670 @c cookies, buckets and records, and the global array of pointers to
671 @c dynamically allocated records is guarded by a non-recursive lock.
672 The @code{telldir} function returns the file position of the directory
673 stream @var{dirstream}.  You can use this value with @code{seekdir} to
674 restore the directory stream to that position.
675 @end deftypefun
677 @deftypefun void seekdir (DIR *@var{dirstream}, long int @var{pos})
678 @standards{BSD, dirent.h}
679 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{/bsd} @asulock{/bsd}}@acunsafe{@acsmem{/bsd} @aculock{/bsd}}}
680 @c The implementation is safe on most platforms, but on BSD it uses
681 @c cookies, buckets and records, and the global array of pointers to
682 @c dynamically allocated records is guarded by a non-recursive lock.
683 The @code{seekdir} function sets the file position of the directory
684 stream @var{dirstream} to @var{pos}.  The value @var{pos} must be the
685 result of a previous call to @code{telldir} on this particular stream;
686 closing and reopening the directory can invalidate values returned by
687 @code{telldir}.
688 @end deftypefun
691 @node Scanning Directory Content
692 @subsection Scanning the Content of a Directory
694 A higher-level interface to the directory handling functions is the
695 @code{scandir} function.  With its help one can select a subset of the
696 entries in a directory, possibly sort them and get a list of names as
697 the result.
699 @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 **))
700 @standards{BSD, dirent.h}
701 @standards{SVID, dirent.h}
702 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
703 @c The scandir function calls __opendirat, __readdir, and __closedir to
704 @c go over the named dir; malloc and realloc to allocate the namelist
705 @c and copies of each selected dirent, besides the selector, if given,
706 @c and qsort and the cmp functions if the latter is given.  In spite of
707 @c the cleanup handler that releases memory and the file descriptor in
708 @c case of synchronous cancellation, an asynchronous cancellation may
709 @c still leak memory and a file descriptor.  Although readdir is unsafe
710 @c in general, the use of an internal dir stream for sequential scanning
711 @c of the directory with copying of dirents before subsequent calls
712 @c makes the use safe, and the fact that the dir stream is private to
713 @c each scandir call does away with the lock issues in readdir and
714 @c closedir.
716 The @code{scandir} function scans the contents of the directory selected
717 by @var{dir}.  The result in *@var{namelist} is an array of pointers to
718 structures of type @code{struct dirent} which describe all selected
719 directory entries and which is allocated using @code{malloc}.  Instead
720 of always getting all directory entries returned, the user supplied
721 function @var{selector} can be used to decide which entries are in the
722 result.  Only the entries for which @var{selector} returns a non-zero
723 value are selected.
725 Finally the entries in *@var{namelist} are sorted using the
726 user-supplied function @var{cmp}.  The arguments passed to the @var{cmp}
727 function are of type @code{struct dirent **}, therefore one cannot
728 directly use the @code{strcmp} or @code{strcoll} functions; instead see
729 the functions @code{alphasort} and @code{versionsort} below.
731 The return value of the function is the number of entries placed in
732 *@var{namelist}.  If it is @code{-1} an error occurred (either the
733 directory could not be opened for reading or the malloc call failed) and
734 the global variable @code{errno} contains more information on the error.
735 @end deftypefun
737 As described above, the fourth argument to the @code{scandir} function
738 must be a pointer to a sorting function.  For the convenience of the
739 programmer @theglibc{} contains implementations of functions which
740 are very helpful for this purpose.
742 @deftypefun int alphasort (const struct dirent **@var{a}, const struct dirent **@var{b})
743 @standards{BSD, dirent.h}
744 @standards{SVID, dirent.h}
745 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
746 @c Calls strcoll.
747 The @code{alphasort} function behaves like the @code{strcoll} function
748 (@pxref{String/Array Comparison}).  The difference is that the arguments
749 are not string pointers but instead they are of type
750 @code{struct dirent **}.
752 The return value of @code{alphasort} is less than, equal to, or greater
753 than zero depending on the order of the two entries @var{a} and @var{b}.
754 @end deftypefun
756 @deftypefun int versionsort (const struct dirent **@var{a}, const struct dirent **@var{b})
757 @standards{GNU, dirent.h}
758 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
759 @c Calls strverscmp, which will accesses the locale object multiple
760 @c times.
761 The @code{versionsort} function is like @code{alphasort} except that it
762 uses the @code{strverscmp} function internally.
763 @end deftypefun
765 If the filesystem supports large files we cannot use the @code{scandir}
766 anymore since the @code{dirent} structure might not able to contain all
767 the information.  The LFS provides the new type @w{@code{struct
768 dirent64}}.  To use this we need a new function.
770 @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 **))
771 @standards{GNU, dirent.h}
772 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
773 @c See scandir.
774 The @code{scandir64} function works like the @code{scandir} function
775 except that the directory entries it returns are described by elements
776 of type @w{@code{struct dirent64}}.  The function pointed to by
777 @var{selector} is again used to select the desired entries, except that
778 @var{selector} now must point to a function which takes a
779 @w{@code{struct dirent64 *}} parameter.
781 Similarly the @var{cmp} function should expect its two arguments to be
782 of type @code{struct dirent64 **}.
783 @end deftypefun
785 As @var{cmp} is now a function of a different type, the functions
786 @code{alphasort} and @code{versionsort} cannot be supplied for that
787 argument.  Instead we provide the two replacement functions below.
789 @deftypefun int alphasort64 (const struct dirent64 **@var{a}, const struct dirent **@var{b})
790 @standards{GNU, dirent.h}
791 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
792 @c See alphasort.
793 The @code{alphasort64} function behaves like the @code{strcoll} function
794 (@pxref{String/Array Comparison}).  The difference is that the arguments
795 are not string pointers but instead they are of type
796 @code{struct dirent64 **}.
798 Return value of @code{alphasort64} is less than, equal to, or greater
799 than zero depending on the order of the two entries @var{a} and @var{b}.
800 @end deftypefun
802 @deftypefun int versionsort64 (const struct dirent64 **@var{a}, const struct dirent64 **@var{b})
803 @standards{GNU, dirent.h}
804 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
805 @c See versionsort.
806 The @code{versionsort64} function is like @code{alphasort64}, excepted that it
807 uses the @code{strverscmp} function internally.
808 @end deftypefun
810 It is important not to mix the use of @code{scandir} and the 64-bit
811 comparison functions or vice versa.  There are systems on which this
812 works but on others it will fail miserably.
814 @node Simple Directory Lister Mark II
815 @subsection Simple Program to List a Directory, Mark II
817 Here is a revised version of the directory lister found above
818 (@pxref{Simple Directory Lister}).  Using the @code{scandir} function we
819 can avoid the functions which work directly with the directory contents.
820 After the call the returned entries are available for direct use.
822 @smallexample
823 @include dir2.c.texi
824 @end smallexample
826 Note the simple selector function in this example.  Since we want to see
827 all directory entries we always return @code{1}.
830 @node Working with Directory Trees
831 @section Working with Directory Trees
832 @cindex directory hierarchy
833 @cindex hierarchy, directory
834 @cindex tree, directory
836 The functions described so far for handling the files in a directory
837 have allowed you to either retrieve the information bit by bit, or to
838 process all the files as a group (see @code{scandir}).  Sometimes it is
839 useful to process whole hierarchies of directories and their contained
840 files.  The X/Open specification defines two functions to do this.  The
841 simpler form is derived from an early definition in @w{System V} systems
842 and therefore this function is available on SVID-derived systems.  The
843 prototypes and required definitions can be found in the @file{ftw.h}
844 header.
846 There are four functions in this family: @code{ftw}, @code{nftw} and
847 their 64-bit counterparts @code{ftw64} and @code{nftw64}.  These
848 functions take as one of their arguments a pointer to a callback
849 function of the appropriate type.
851 @deftp {Data Type} __ftw_func_t
852 @standards{GNU, ftw.h}
854 @smallexample
855 int (*) (const char *, const struct stat *, int)
856 @end smallexample
858 The type of callback functions given to the @code{ftw} function.  The
859 first parameter points to the file name, the second parameter to an
860 object of type @code{struct stat} which is filled in for the file named
861 in the first parameter.
863 @noindent
864 The last parameter is a flag giving more information about the current
865 file.  It can have the following values:
867 @vtable @code
868 @item FTW_F
869 The item is either a normal file or a file which does not fit into one
870 of the following categories.  This could be special files, sockets etc.
871 @item FTW_D
872 The item is a directory.
873 @item FTW_NS
874 The @code{stat} call failed and so the information pointed to by the
875 second parameter is invalid.
876 @item FTW_DNR
877 The item is a directory which cannot be read.
878 @item FTW_SL
879 The item is a symbolic link.  Since symbolic links are normally followed
880 seeing this value in a @code{ftw} callback function means the referenced
881 file does not exist.  The situation for @code{nftw} is different.
883 This value is only available if the program is compiled with
884 @code{_XOPEN_EXTENDED} defined before including
885 the first header.  The original SVID systems do not have symbolic links.
886 @end vtable
888 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
889 type is in fact @code{__ftw64_func_t} since this mode changes
890 @code{struct stat} to be @code{struct stat64}.
891 @end deftp
893 For the LFS interface and for use in the function @code{ftw64}, the
894 header @file{ftw.h} defines another function type.
896 @deftp {Data Type} __ftw64_func_t
897 @standards{GNU, ftw.h}
899 @smallexample
900 int (*) (const char *, const struct stat64 *, int)
901 @end smallexample
903 This type is used just like @code{__ftw_func_t} for the callback
904 function, but this time is called from @code{ftw64}.  The second
905 parameter to the function is a pointer to a variable of type
906 @code{struct stat64} which is able to represent the larger values.
907 @end deftp
909 @deftp {Data Type} __nftw_func_t
910 @standards{GNU, ftw.h}
912 @smallexample
913 int (*) (const char *, const struct stat *, int, struct FTW *)
914 @end smallexample
916 The first three arguments are the same as for the @code{__ftw_func_t}
917 type.  However for the third argument some additional values are defined
918 to allow finer differentiation:
919 @vtable @code
920 @item FTW_DP
921 The current item is a directory and all subdirectories have already been
922 visited and reported.  This flag is returned instead of @code{FTW_D} if
923 the @code{FTW_DEPTH} flag is passed to @code{nftw} (see below).
924 @item FTW_SLN
925 The current item is a stale symbolic link.  The file it points to does
926 not exist.
927 @end vtable
929 The last parameter of the callback function is a pointer to a structure
930 with some extra information as described below.
932 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
933 type is in fact @code{__nftw64_func_t} since this mode changes
934 @code{struct stat} to be @code{struct stat64}.
935 @end deftp
937 For the LFS interface there is also a variant of this data type
938 available which has to be used with the @code{nftw64} function.
940 @deftp {Data Type} __nftw64_func_t
941 @standards{GNU, ftw.h}
943 @smallexample
944 int (*) (const char *, const struct stat64 *, int, struct FTW *)
945 @end smallexample
947 This type is used just like @code{__nftw_func_t} for the callback
948 function, but this time is called from @code{nftw64}.  The second
949 parameter to the function is this time a pointer to a variable of type
950 @code{struct stat64} which is able to represent the larger values.
951 @end deftp
953 @deftp {Data Type} {struct FTW}
954 @standards{XPG4.2, ftw.h}
955 The information contained in this structure helps in interpreting the
956 name parameter and gives some information about the current state of the
957 traversal of the directory hierarchy.
959 @table @code
960 @item int base
961 The value is the offset into the string passed in the first parameter to
962 the callback function of the beginning of the file name.  The rest of
963 the string is the path of the file.  This information is especially
964 important if the @code{FTW_CHDIR} flag was set in calling @code{nftw}
965 since then the current directory is the one the current item is found
967 @item int level
968 Whilst processing, the code tracks how many directories down it has gone
969 to find the current file.  This nesting level starts at @math{0} for
970 files in the initial directory (or is zero for the initial file if a
971 file was passed).
972 @end table
973 @end deftp
976 @deftypefun int ftw (const char *@var{filename}, __ftw_func_t @var{func}, int @var{descriptors})
977 @standards{SVID, ftw.h}
978 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
979 @c see nftw for safety details
980 The @code{ftw} function calls the callback function given in the
981 parameter @var{func} for every item which is found in the directory
982 specified by @var{filename} and all directories below.  The function
983 follows symbolic links if necessary but does not process an item twice.
984 If @var{filename} is not a directory then it itself is the only object
985 returned to the callback function.
987 The file name passed to the callback function is constructed by taking
988 the @var{filename} parameter and appending the names of all passed
989 directories and then the local file name.  So the callback function can
990 use this parameter to access the file.  @code{ftw} also calls
991 @code{stat} for the file and passes that information on to the callback
992 function.  If this @code{stat} call is not successful the failure is
993 indicated by setting the third argument of the callback function to
994 @code{FTW_NS}.  Otherwise it is set according to the description given
995 in the account of @code{__ftw_func_t} above.
997 The callback function is expected to return @math{0} to indicate that no
998 error occurred and that processing should continue.  If an error
999 occurred in the callback function or it wants @code{ftw} to return
1000 immediately, the callback function can return a value other than
1001 @math{0}.  This is the only correct way to stop the function.  The
1002 program must not use @code{setjmp} or similar techniques to continue
1003 from another place.  This would leave resources allocated by the
1004 @code{ftw} function unfreed.
1006 The @var{descriptors} parameter to @code{ftw} specifies how many file
1007 descriptors it is allowed to consume.  The function runs faster the more
1008 descriptors it can use.  For each level in the directory hierarchy at
1009 most one descriptor is used, but for very deep ones any limit on open
1010 file descriptors for the process or the system may be exceeded.
1011 Moreover, file descriptor limits in a multi-threaded program apply to
1012 all the threads as a group, and therefore it is a good idea to supply a
1013 reasonable limit to the number of open descriptors.
1015 The return value of the @code{ftw} function is @math{0} if all callback
1016 function calls returned @math{0} and all actions performed by the
1017 @code{ftw} succeeded.  If a function call failed (other than calling
1018 @code{stat} on an item) the function returns @math{-1}.  If a callback
1019 function returns a value other than @math{0} this value is returned as
1020 the return value of @code{ftw}.
1022 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1023 32-bit system this function is in fact @code{ftw64}, i.e., the LFS
1024 interface transparently replaces the old interface.
1025 @end deftypefun
1027 @deftypefun int ftw64 (const char *@var{filename}, __ftw64_func_t @var{func}, int @var{descriptors})
1028 @standards{Unix98, ftw.h}
1029 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
1030 This function is similar to @code{ftw} but it can work on filesystems
1031 with large files.  File information is reported using a variable of type
1032 @code{struct stat64} which is passed by reference to the callback
1033 function.
1035 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1036 32-bit system this function is available under the name @code{ftw} and
1037 transparently replaces the old implementation.
1038 @end deftypefun
1040 @deftypefun int nftw (const char *@var{filename}, __nftw_func_t @var{func}, int @var{descriptors}, int @var{flag})
1041 @standards{XPG4.2, ftw.h}
1042 @safety{@prelim{}@mtsafe{@mtasscwd{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{} @acscwd{}}}
1043 @c ftw_startup calls alloca, malloc, free, xstat/lxstat, tdestroy, and ftw_dir
1044 @c  if FTW_CHDIR, call open, and fchdir, or chdir and getcwd
1045 @c ftw_dir calls open_dir_stream, readdir64, process_entry, closedir
1046 @c  if FTW_CHDIR, also calls fchdir
1047 @c open_dir_stream calls malloc, realloc, readdir64, free, closedir,
1048 @c  then openat64_not_cancel_3 and fdopendir or opendir, then dirfd.
1049 @c process_entry may cal realloc, fxstatat/lxstat/xstat, ftw_dir, and
1050 @c  find_object (tsearch) and add_object (tfind).
1051 @c Since each invocation of *ftw uses its own private search tree, none
1052 @c  of the search tree concurrency issues apply.
1053 The @code{nftw} function works like the @code{ftw} functions.  They call
1054 the callback function @var{func} for all items found in the directory
1055 @var{filename} and below.  At most @var{descriptors} file descriptors
1056 are consumed during the @code{nftw} call.
1058 One difference is that the callback function is of a different type.  It
1059 is of type @w{@code{struct FTW *}} and provides the callback function
1060 with the extra information described above.
1062 A second difference is that @code{nftw} takes a fourth argument, which
1063 is @math{0} or a bitwise-OR combination of any of the following values.
1065 @vtable @code
1066 @item FTW_PHYS
1067 While traversing the directory symbolic links are not followed.  Instead
1068 symbolic links are reported using the @code{FTW_SL} value for the type
1069 parameter to the callback function.  If the file referenced by a
1070 symbolic link does not exist @code{FTW_SLN} is returned instead.
1071 @item FTW_MOUNT
1072 The callback function is only called for items which are on the same
1073 mounted filesystem as the directory given by the @var{filename}
1074 parameter to @code{nftw}.
1075 @item FTW_CHDIR
1076 If this flag is given the current working directory is changed to the
1077 directory of the reported object before the callback function is called.
1078 When @code{ntfw} finally returns the current directory is restored to
1079 its original value.
1080 @item FTW_DEPTH
1081 If this option is specified then all subdirectories and files within
1082 them are processed before processing the top directory itself
1083 (depth-first processing).  This also means the type flag given to the
1084 callback function is @code{FTW_DP} and not @code{FTW_D}.
1085 @item FTW_ACTIONRETVAL
1086 If this option is specified then return values from callbacks
1087 are handled differently.  If the callback returns @code{FTW_CONTINUE},
1088 walking continues normally.  @code{FTW_STOP} means walking stops
1089 and @code{FTW_STOP} is returned to the caller.  If @code{FTW_SKIP_SUBTREE}
1090 is returned by the callback with @code{FTW_D} argument, the subtree
1091 is skipped and walking continues with next sibling of the directory.
1092 If @code{FTW_SKIP_SIBLINGS} is returned by the callback, all siblings
1093 of the current entry are skipped and walking continues in its parent.
1094 No other return values should be returned from the callbacks if
1095 this option is set.  This option is a GNU extension.
1096 @end vtable
1098 The return value is computed in the same way as for @code{ftw}.
1099 @code{nftw} returns @math{0} if no failures occurred and all callback
1100 functions returned @math{0}.  In case of internal errors, such as memory
1101 problems, the return value is @math{-1} and @var{errno} is set
1102 accordingly.  If the return value of a callback invocation was non-zero
1103 then that value is returned.
1105 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1106 32-bit system this function is in fact @code{nftw64}, i.e., the LFS
1107 interface transparently replaces the old interface.
1108 @end deftypefun
1110 @deftypefun int nftw64 (const char *@var{filename}, __nftw64_func_t @var{func}, int @var{descriptors}, int @var{flag})
1111 @standards{Unix98, ftw.h}
1112 @safety{@prelim{}@mtsafe{@mtasscwd{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{} @acscwd{}}}
1113 This function is similar to @code{nftw} but it can work on filesystems
1114 with large files.  File information is reported using a variable of type
1115 @code{struct stat64} which is passed by reference to the callback
1116 function.
1118 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
1119 32-bit system this function is available under the name @code{nftw} and
1120 transparently replaces the old implementation.
1121 @end deftypefun
1124 @node Hard Links
1125 @section Hard Links
1126 @cindex hard link
1127 @cindex link, hard
1128 @cindex multiple names for one file
1129 @cindex file names, multiple
1131 In POSIX systems, one file can have many names at the same time.  All of
1132 the names are equally real, and no one of them is preferred to the
1133 others.
1135 To add a name to a file, use the @code{link} function.  (The new name is
1136 also called a @dfn{hard link} to the file.)  Creating a new link to a
1137 file does not copy the contents of the file; it simply makes a new name
1138 by which the file can be known, in addition to the file's existing name
1139 or names.
1141 One file can have names in several directories, so the organization
1142 of the file system is not a strict hierarchy or tree.
1144 In most implementations, it is not possible to have hard links to the
1145 same file in multiple file systems.  @code{link} reports an error if you
1146 try to make a hard link to the file from another file system when this
1147 cannot be done.
1149 The prototype for the @code{link} function is declared in the header
1150 file @file{unistd.h}.
1151 @pindex unistd.h
1153 @deftypefun int link (const char *@var{oldname}, const char *@var{newname})
1154 @standards{POSIX.1, unistd.h}
1155 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1156 The @code{link} function makes a new link to the existing file named by
1157 @var{oldname}, under the new name @var{newname}.
1159 This function returns a value of @code{0} if it is successful and
1160 @code{-1} on failure.  In addition to the usual file name errors
1161 (@pxref{File Name Errors}) for both @var{oldname} and @var{newname}, the
1162 following @code{errno} error conditions are defined for this function:
1164 @table @code
1165 @item EACCES
1166 You are not allowed to write to the directory in which the new link is
1167 to be written.
1168 @ignore
1169 Some implementations also require that the existing file be accessible
1170 by the caller, and use this error to report failure for that reason.
1171 @end ignore
1173 @item EEXIST
1174 There is already a file named @var{newname}.  If you want to replace
1175 this link with a new link, you must remove the old link explicitly first.
1177 @item EMLINK
1178 There are already too many links to the file named by @var{oldname}.
1179 (The maximum number of links to a file is @w{@code{LINK_MAX}}; see
1180 @ref{Limits for Files}.)
1182 @item ENOENT
1183 The file named by @var{oldname} doesn't exist.  You can't make a link to
1184 a file that doesn't exist.
1186 @item ENOSPC
1187 The directory or file system that would contain the new link is full
1188 and cannot be extended.
1190 @item EPERM
1191 On @gnulinuxhurdsystems{} and some others, you cannot make links to
1192 directories.
1193 Many systems allow only privileged users to do so.  This error
1194 is used to report the problem.
1196 @item EROFS
1197 The directory containing the new link can't be modified because it's on
1198 a read-only file system.
1200 @item EXDEV
1201 The directory specified in @var{newname} is on a different file system
1202 than the existing file.
1204 @item EIO
1205 A hardware error occurred while trying to read or write the to filesystem.
1206 @end table
1207 @end deftypefun
1209 @deftypefun int linkat (int oldfd, const char *@var{oldname}, int newfd, const char *@var{newname}, int flags)
1210 @standards{POSIX.1, unistd.h}
1211 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1213 The @code{linkat} function is analogous to the @code{link} function,
1214 except that it identifies its source and target using a combination of a
1215 file descriptor (referring to a directory) and a pathname.  If a
1216 pathnames is not absolute, it is resolved relative to the corresponding
1217 file descriptor.  The special file descriptor @code{AT_FDCWD} denotes
1218 the current directory.
1220 The @var{flags} argument is a combination of the following flags:
1222 @table @code
1223 @item AT_SYMLINK_FOLLOW
1224 If the source path identified by @var{oldfd} and @var{oldname} is a
1225 symbolic link, @code{linkat} follows the symbolic link and creates a
1226 link to its target.  If the flag is not set, a link for the symbolic
1227 link itself is created; this is not supported by all file systems and
1228 @code{linkat} can fail in this case.
1230 @item AT_EMPTY_PATH
1231 If this flag is specified, @var{oldname} can be an empty string.  In
1232 this case, a new link to the file denoted by the descriptor @var{oldfd}
1233 is created, which may have been opened with @code{O_PATH} or
1234 @code{O_TMPFILE}.  This flag is a GNU extension.
1235 @end table
1236 @end deftypefun
1238 @node Symbolic Links
1239 @section Symbolic Links
1240 @cindex soft link
1241 @cindex link, soft
1242 @cindex symbolic link
1243 @cindex link, symbolic
1245 @gnusystems{} support @dfn{soft links} or @dfn{symbolic links}.  This
1246 is a kind of ``file'' that is essentially a pointer to another file
1247 name.  Unlike hard links, symbolic links can be made to directories or
1248 across file systems with no restrictions.  You can also make a symbolic
1249 link to a name which is not the name of any file.  (Opening this link
1250 will fail until a file by that name is created.)  Likewise, if the
1251 symbolic link points to an existing file which is later deleted, the
1252 symbolic link continues to point to the same file name even though the
1253 name no longer names any file.
1255 The reason symbolic links work the way they do is that special things
1256 happen when you try to open the link.  The @code{open} function realizes
1257 you have specified the name of a link, reads the file name contained in
1258 the link, and opens that file name instead.  The @code{stat} function
1259 likewise operates on the file that the symbolic link points to, instead
1260 of on the link itself.
1262 By contrast, other operations such as deleting or renaming the file
1263 operate on the link itself.  The functions @code{readlink} and
1264 @code{lstat} also refrain from following symbolic links, because their
1265 purpose is to obtain information about the link.  @code{link}, the
1266 function that makes a hard link, does too.  It makes a hard link to the
1267 symbolic link, which one rarely wants.
1269 Some systems have, for some functions operating on files, a limit on
1270 how many symbolic links are followed when resolving a path name.  The
1271 limit if it exists is published in the @file{sys/param.h} header file.
1273 @deftypevr Macro int MAXSYMLINKS
1274 @standards{BSD, sys/param.h}
1276 The macro @code{MAXSYMLINKS} specifies how many symlinks some function
1277 will follow before returning @code{ELOOP}.  Not all functions behave the
1278 same and this value is not the same as that returned for
1279 @code{_SC_SYMLOOP} by @code{sysconf}.  In fact, the @code{sysconf}
1280 result can indicate that there is no fixed limit although
1281 @code{MAXSYMLINKS} exists and has a finite value.
1282 @end deftypevr
1284 Prototypes for most of the functions listed in this section are in
1285 @file{unistd.h}.
1286 @pindex unistd.h
1288 @deftypefun int symlink (const char *@var{oldname}, const char *@var{newname})
1289 @standards{BSD, unistd.h}
1290 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1291 The @code{symlink} function makes a symbolic link to @var{oldname} named
1292 @var{newname}.
1294 The normal return value from @code{symlink} is @code{0}.  A return value
1295 of @code{-1} indicates an error.  In addition to the usual file name
1296 syntax errors (@pxref{File Name Errors}), the following @code{errno}
1297 error conditions are defined for this function:
1299 @table @code
1300 @item EEXIST
1301 There is already an existing file named @var{newname}.
1303 @item EROFS
1304 The file @var{newname} would exist on a read-only file system.
1306 @item ENOSPC
1307 The directory or file system cannot be extended to make the new link.
1309 @item EIO
1310 A hardware error occurred while reading or writing data on the disk.
1312 @comment not sure about these
1313 @ignore
1314 @item ELOOP
1315 There are too many levels of indirection.  This can be the result of
1316 circular symbolic links to directories.
1318 @item EDQUOT
1319 The new link can't be created because the user's disk quota has been
1320 exceeded.
1321 @end ignore
1322 @end table
1323 @end deftypefun
1325 @deftypefun ssize_t readlink (const char *@var{filename}, char *@var{buffer}, size_t @var{size})
1326 @standards{BSD, unistd.h}
1327 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1328 The @code{readlink} function gets the value of the symbolic link
1329 @var{filename}.  The file name that the link points to is copied into
1330 @var{buffer}.  This file name string is @emph{not} null-terminated;
1331 @code{readlink} normally returns the number of characters copied.  The
1332 @var{size} argument specifies the maximum number of characters to copy,
1333 usually the allocation size of @var{buffer}.
1335 If the return value equals @var{size}, you cannot tell whether or not
1336 there was room to return the entire name.  So make a bigger buffer and
1337 call @code{readlink} again.  Here is an example:
1339 @smallexample
1340 char *
1341 readlink_malloc (const char *filename)
1343   int size = 100;
1344   char *buffer = NULL;
1346   while (1)
1347     @{
1348       buffer = (char *) xrealloc (buffer, size);
1349       int nchars = readlink (filename, buffer, size);
1350       if (nchars < 0)
1351         @{
1352           free (buffer);
1353           return NULL;
1354         @}
1355       if (nchars < size)
1356         return buffer;
1357       size *= 2;
1358     @}
1360 @end smallexample
1362 @c @group  Invalid outside example.
1363 A value of @code{-1} is returned in case of error.  In addition to the
1364 usual file name errors (@pxref{File Name Errors}), the following
1365 @code{errno} error conditions are defined for this function:
1367 @table @code
1368 @item EINVAL
1369 The named file is not a symbolic link.
1371 @item EIO
1372 A hardware error occurred while reading or writing data on the disk.
1373 @end table
1374 @c @end group
1375 @end deftypefun
1377 In some situations it is desirable to resolve all the
1378 symbolic links to get the real
1379 name of a file where no prefix names a symbolic link which is followed
1380 and no filename in the path is @code{.} or @code{..}.  This is for
1381 instance desirable if files have to be compared in which case different
1382 names can refer to the same inode.
1384 @deftypefun {char *} canonicalize_file_name (const char *@var{name})
1385 @standards{GNU, stdlib.h}
1386 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
1387 @c Calls realpath.
1389 The @code{canonicalize_file_name} function returns the absolute name of
1390 the file named by @var{name} which contains no @code{.}, @code{..}
1391 components nor any repeated path separators (@code{/}) or symlinks.  The
1392 result is passed back as the return value of the function in a block of
1393 memory allocated with @code{malloc}.  If the result is not used anymore
1394 the memory should be freed with a call to @code{free}.
1396 If any of the path components are missing the function returns a NULL
1397 pointer.  This is also what is returned if the length of the path
1398 reaches or exceeds @code{PATH_MAX} characters.  In any case
1399 @code{errno} is set accordingly.
1401 @table @code
1402 @item ENAMETOOLONG
1403 The resulting path is too long.  This error only occurs on systems which
1404 have a limit on the file name length.
1406 @item EACCES
1407 At least one of the path components is not readable.
1409 @item ENOENT
1410 The input file name is empty.
1412 @item ENOENT
1413 At least one of the path components does not exist.
1415 @item ELOOP
1416 More than @code{MAXSYMLINKS} many symlinks have been followed.
1417 @end table
1419 This function is a GNU extension and is declared in @file{stdlib.h}.
1420 @end deftypefun
1422 The Unix standard includes a similar function which differs from
1423 @code{canonicalize_file_name} in that the user has to provide the buffer
1424 where the result is placed in.
1426 @deftypefun {char *} realpath (const char *restrict @var{name}, char *restrict @var{resolved})
1427 @standards{XPG, stdlib.h}
1428 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{} @acsfd{}}}
1429 @c Calls malloc, realloc, getcwd, lxstat64, readlink, alloca.
1431 A call to @code{realpath} where the @var{resolved} parameter is
1432 @code{NULL} behaves exactly like @code{canonicalize_file_name}.  The
1433 function allocates a buffer for the file name and returns a pointer to
1434 it.  If @var{resolved} is not @code{NULL} it points to a buffer into
1435 which the result is copied.  It is the callers responsibility to
1436 allocate a buffer which is large enough.  On systems which define
1437 @code{PATH_MAX} this means the buffer must be large enough for a
1438 pathname of this size.  For systems without limitations on the pathname
1439 length the requirement cannot be met and programs should not call
1440 @code{realpath} with anything but @code{NULL} for the second parameter.
1442 One other difference is that the buffer @var{resolved} (if nonzero) will
1443 contain the part of the path component which does not exist or is not
1444 readable if the function returns @code{NULL} and @code{errno} is set to
1445 @code{EACCES} or @code{ENOENT}.
1447 This function is declared in @file{stdlib.h}.
1448 @end deftypefun
1450 The advantage of using this function is that it is more widely
1451 available.  The drawback is that it reports failures for long paths on
1452 systems which have no limits on the file name length.
1454 @node Deleting Files
1455 @section Deleting Files
1456 @cindex deleting a file
1457 @cindex removing a file
1458 @cindex unlinking a file
1460 You can delete a file with @code{unlink} or @code{remove}.
1462 Deletion actually deletes a file name.  If this is the file's only name,
1463 then the file is deleted as well.  If the file has other remaining names
1464 (@pxref{Hard Links}), it remains accessible under those names.
1466 @deftypefun int unlink (const char *@var{filename})
1467 @standards{POSIX.1, unistd.h}
1468 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1469 The @code{unlink} function deletes the file name @var{filename}.  If
1470 this is a file's sole name, the file itself is also deleted.  (Actually,
1471 if any process has the file open when this happens, deletion is
1472 postponed until all processes have closed the file.)
1474 @pindex unistd.h
1475 The function @code{unlink} is declared in the header file @file{unistd.h}.
1477 This function returns @code{0} on successful completion, and @code{-1}
1478 on error.  In addition to the usual file name errors
1479 (@pxref{File Name Errors}), the following @code{errno} error conditions are
1480 defined for this function:
1482 @table @code
1483 @item EACCES
1484 Write permission is denied for the directory from which the file is to be
1485 removed, or the directory has the sticky bit set and you do not own the file.
1487 @item EBUSY
1488 This error indicates that the file is being used by the system in such a
1489 way that it can't be unlinked.  For example, you might see this error if
1490 the file name specifies the root directory or a mount point for a file
1491 system.
1493 @item ENOENT
1494 The file name to be deleted doesn't exist.
1496 @item EPERM
1497 On some systems @code{unlink} cannot be used to delete the name of a
1498 directory, or at least can only be used this way by a privileged user.
1499 To avoid such problems, use @code{rmdir} to delete directories.  (On
1500 @gnulinuxhurdsystems{} @code{unlink} can never delete the name of a directory.)
1502 @item EROFS
1503 The directory containing the file name to be deleted is on a read-only
1504 file system and can't be modified.
1505 @end table
1506 @end deftypefun
1508 @deftypefun int rmdir (const char *@var{filename})
1509 @standards{POSIX.1, unistd.h}
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 @deftypefun int remove (const char *@var{filename})
1536 @standards{ISO, stdio.h}
1537 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1538 @c Calls unlink and rmdir.
1539 This is the @w{ISO C} function to remove a file.  It works like
1540 @code{unlink} for files and like @code{rmdir} for directories.
1541 @code{remove} is declared in @file{stdio.h}.
1542 @pindex stdio.h
1543 @end deftypefun
1545 @node Renaming Files
1546 @section Renaming Files
1548 The @code{rename} function is used to change a file's name.
1550 @cindex renaming a file
1551 @deftypefun int rename (const char *@var{oldname}, const char *@var{newname})
1552 @standards{ISO, stdio.h}
1553 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1554 @c In the absence of a rename syscall, there's an emulation with link
1555 @c and unlink, but it's racy, even more so if newname exists and is
1556 @c unlinked first.
1557 The @code{rename} function renames the file @var{oldname} to
1558 @var{newname}.  The file formerly accessible under the name
1559 @var{oldname} is afterwards accessible as @var{newname} instead.  (If
1560 the file had any other names aside from @var{oldname}, it continues to
1561 have those names.)
1563 The directory containing the name @var{newname} must be on the same file
1564 system as the directory containing the name @var{oldname}.
1566 One special case for @code{rename} is when @var{oldname} and
1567 @var{newname} are two names for the same file.  The consistent way to
1568 handle this case is to delete @var{oldname}.  However, in this case
1569 POSIX requires that @code{rename} do nothing and report success---which
1570 is inconsistent.  We don't know what your operating system will do.
1572 If @var{oldname} is not a directory, then any existing file named
1573 @var{newname} is removed during the renaming operation.  However, if
1574 @var{newname} is the name of a directory, @code{rename} fails in this
1575 case.
1577 If @var{oldname} is a directory, then either @var{newname} must not
1578 exist or it must name a directory that is empty.  In the latter case,
1579 the existing directory named @var{newname} is deleted first.  The name
1580 @var{newname} must not specify a subdirectory of the directory
1581 @code{oldname} which is being renamed.
1583 One useful feature of @code{rename} is that the meaning of @var{newname}
1584 changes ``atomically'' from any previously existing file by that name to
1585 its new meaning (i.e., the file that was called @var{oldname}).  There is
1586 no instant at which @var{newname} is non-existent ``in between'' the old
1587 meaning and the new meaning.  If there is a system crash during the
1588 operation, it is possible for both names to still exist; but
1589 @var{newname} will always be intact if it exists at all.
1591 If @code{rename} fails, it returns @code{-1}.  In addition to the usual
1592 file name errors (@pxref{File Name Errors}), the following
1593 @code{errno} error conditions are defined for this function:
1595 @table @code
1596 @item EACCES
1597 One of the directories containing @var{newname} or @var{oldname}
1598 refuses write permission; or @var{newname} and @var{oldname} are
1599 directories and write permission is refused for one of them.
1601 @item EBUSY
1602 A directory named by @var{oldname} or @var{newname} is being used by
1603 the system in a way that prevents the renaming from working.  This includes
1604 directories that are mount points for filesystems, and directories
1605 that are the current working directories of processes.
1607 @item ENOTEMPTY
1608 @itemx EEXIST
1609 The directory @var{newname} isn't empty.  @gnulinuxhurdsystems{} always return
1610 @code{ENOTEMPTY} for this, but some other systems return @code{EEXIST}.
1612 @item EINVAL
1613 @var{oldname} is a directory that contains @var{newname}.
1615 @item EISDIR
1616 @var{newname} is a directory but the @var{oldname} isn't.
1618 @item EMLINK
1619 The parent directory of @var{newname} would have too many links
1620 (entries).
1622 @item ENOENT
1623 The file @var{oldname} doesn't exist.
1625 @item ENOSPC
1626 The directory that would contain @var{newname} has no room for another
1627 entry, and there is no space left in the file system to expand it.
1629 @item EROFS
1630 The operation would involve writing to a directory on a read-only file
1631 system.
1633 @item EXDEV
1634 The two file names @var{newname} and @var{oldname} are on different
1635 file systems.
1636 @end table
1637 @end deftypefun
1639 @node Creating Directories
1640 @section Creating Directories
1641 @cindex creating a directory
1642 @cindex directories, creating
1644 @pindex mkdir
1645 Directories are created with the @code{mkdir} function.  (There is also
1646 a shell command @code{mkdir} which does the same thing.)
1647 @c !!! umask
1649 @deftypefun int mkdir (const char *@var{filename}, mode_t @var{mode})
1650 @standards{POSIX.1, sys/stat.h}
1651 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1652 The @code{mkdir} function creates a new, empty directory with name
1653 @var{filename}.
1655 The argument @var{mode} specifies the file permissions for the new
1656 directory file.  @xref{Permission Bits}, for more information about
1657 this.
1659 A return value of @code{0} indicates successful completion, and
1660 @code{-1} indicates failure.  In addition to the usual file name syntax
1661 errors (@pxref{File Name Errors}), the following @code{errno} error
1662 conditions are defined for this function:
1664 @table @code
1665 @item EACCES
1666 Write permission is denied for the parent directory in which the new
1667 directory is to be added.
1669 @item EEXIST
1670 A file named @var{filename} already exists.
1672 @item EMLINK
1673 The parent directory has too many links (entries).
1675 Well-designed file systems never report this error, because they permit
1676 more links than your disk could possibly hold.  However, you must still
1677 take account of the possibility of this error, as it could result from
1678 network access to a file system on another machine.
1680 @item ENOSPC
1681 The file system doesn't have enough room to create the new directory.
1683 @item EROFS
1684 The parent directory of the directory being created is on a read-only
1685 file system and cannot be modified.
1686 @end table
1688 To use this function, your program should include the header file
1689 @file{sys/stat.h}.
1690 @pindex sys/stat.h
1691 @end deftypefun
1693 @node File Attributes
1694 @section File Attributes
1696 @pindex ls
1697 When you issue an @samp{ls -l} shell command on a file, it gives you
1698 information about the size of the file, who owns it, when it was last
1699 modified, etc.  These are called the @dfn{file attributes}, and are
1700 associated with the file itself and not a particular one of its names.
1702 This section contains information about how you can inquire about and
1703 modify the attributes of a file.
1705 @menu
1706 * Attribute Meanings::          The names of the file attributes,
1707                                  and what their values mean.
1708 * Reading Attributes::          How to read the attributes of a file.
1709 * Testing File Type::           Distinguishing ordinary files,
1710                                  directories, links@dots{}
1711 * File Owner::                  How ownership for new files is determined,
1712                                  and how to change it.
1713 * Permission Bits::             How information about a file's access
1714                                  mode is stored.
1715 * Access Permission::           How the system decides who can access a file.
1716 * Setting Permissions::         How permissions for new files are assigned,
1717                                  and how to change them.
1718 * Testing File Access::         How to find out if your process can
1719                                  access a file.
1720 * File Times::                  About the time attributes of a file.
1721 * File Size::                   Manually changing the size of a file.
1722 * Storage Allocation::          Allocate backing storage for files.
1723 @end menu
1725 @node Attribute Meanings
1726 @subsection The meaning of the File Attributes
1727 @cindex status of a file
1728 @cindex attributes of a file
1729 @cindex file attributes
1731 When you read the attributes of a file, they come back in a structure
1732 called @code{struct stat}.  This section describes the names of the
1733 attributes, their data types, and what they mean.  For the functions
1734 to read the attributes of a file, see @ref{Reading Attributes}.
1736 The header file @file{sys/stat.h} declares all the symbols defined
1737 in this section.
1738 @pindex sys/stat.h
1740 @deftp {Data Type} {struct stat}
1741 @standards{POSIX.1, sys/stat.h}
1742 The @code{stat} structure type is used to return information about the
1743 attributes of a file.  It contains at least the following members:
1745 @table @code
1746 @item mode_t st_mode
1747 Specifies the mode of the file.  This includes file type information
1748 (@pxref{Testing File Type}) and the file permission bits
1749 (@pxref{Permission Bits}).
1751 @item ino_t st_ino
1752 The file serial number, which distinguishes this file from all other
1753 files on the same device.
1755 @item dev_t st_dev
1756 Identifies the device containing the file.  The @code{st_ino} and
1757 @code{st_dev}, taken together, uniquely identify the file.  The
1758 @code{st_dev} value is not necessarily consistent across reboots or
1759 system crashes, however.
1761 @item nlink_t st_nlink
1762 The number of hard links to the file.  This count keeps track of how
1763 many directories have entries for this file.  If the count is ever
1764 decremented to zero, then the file itself is discarded as soon as no
1765 process still holds it open.  Symbolic links are not counted in the
1766 total.
1768 @item uid_t st_uid
1769 The user ID of the file's owner.  @xref{File Owner}.
1771 @item gid_t st_gid
1772 The group ID of the file.  @xref{File Owner}.
1774 @item off_t st_size
1775 This specifies the size of a regular file in bytes.  For files that are
1776 really devices this field isn't usually meaningful.  For symbolic links
1777 this specifies the length of the file name the link refers to.
1779 @item time_t st_atime
1780 This is the last access time for the file.  @xref{File Times}.
1782 @item unsigned long int st_atime_usec
1783 This is the fractional part of the last access time for the file.
1784 @xref{File Times}.
1786 @item time_t st_mtime
1787 This is the time of the last modification to the contents of the file.
1788 @xref{File Times}.
1790 @item unsigned long int st_mtime_usec
1791 This is the fractional part of the time of the last modification to the
1792 contents of the file.  @xref{File Times}.
1794 @item time_t st_ctime
1795 This is the time of the last modification to the attributes of the file.
1796 @xref{File Times}.
1798 @item unsigned long int st_ctime_usec
1799 This is the fractional part of the time of the last modification to the
1800 attributes of the file.  @xref{File Times}.
1802 @c !!! st_rdev
1803 @item blkcnt_t st_blocks
1804 This is the amount of disk space that the file occupies, measured in
1805 units of 512-byte blocks.
1807 The number of disk blocks is not strictly proportional to the size of
1808 the file, for two reasons: the file system may use some blocks for
1809 internal record keeping; and the file may be sparse---it may have
1810 ``holes'' which contain zeros but do not actually take up space on the
1811 disk.
1813 You can tell (approximately) whether a file is sparse by comparing this
1814 value with @code{st_size}, like this:
1816 @smallexample
1817 (st.st_blocks * 512 < st.st_size)
1818 @end smallexample
1820 This test is not perfect because a file that is just slightly sparse
1821 might not be detected as sparse at all.  For practical applications,
1822 this is not a problem.
1824 @item unsigned int st_blksize
1825 The optimal block size for reading or writing this file, in bytes.  You
1826 might use this size for allocating the buffer space for reading or
1827 writing the file.  (This is unrelated to @code{st_blocks}.)
1828 @end table
1829 @end deftp
1831 The extensions for the Large File Support (LFS) require, even on 32-bit
1832 machines, types which can handle file sizes up to @twoexp{63}.
1833 Therefore a new definition of @code{struct stat} is necessary.
1835 @deftp {Data Type} {struct stat64}
1836 @standards{LFS, sys/stat.h}
1837 The members of this type are the same and have the same names as those
1838 in @code{struct stat}.  The only difference is that the members
1839 @code{st_ino}, @code{st_size}, and @code{st_blocks} have a different
1840 type to support larger values.
1842 @table @code
1843 @item mode_t st_mode
1844 Specifies the mode of the file.  This includes file type information
1845 (@pxref{Testing File Type}) and the file permission bits
1846 (@pxref{Permission Bits}).
1848 @item ino64_t st_ino
1849 The file serial number, which distinguishes this file from all other
1850 files on the same device.
1852 @item dev_t st_dev
1853 Identifies the device containing the file.  The @code{st_ino} and
1854 @code{st_dev}, taken together, uniquely identify the file.  The
1855 @code{st_dev} value is not necessarily consistent across reboots or
1856 system crashes, however.
1858 @item nlink_t st_nlink
1859 The number of hard links to the file.  This count keeps track of how
1860 many directories have entries for this file.  If the count is ever
1861 decremented to zero, then the file itself is discarded as soon as no
1862 process still holds it open.  Symbolic links are not counted in the
1863 total.
1865 @item uid_t st_uid
1866 The user ID of the file's owner.  @xref{File Owner}.
1868 @item gid_t st_gid
1869 The group ID of the file.  @xref{File Owner}.
1871 @item off64_t st_size
1872 This specifies the size of a regular file in bytes.  For files that are
1873 really devices this field isn't usually meaningful.  For symbolic links
1874 this specifies the length of the file name the link refers to.
1876 @item time_t st_atime
1877 This is the last access time for the file.  @xref{File Times}.
1879 @item unsigned long int st_atime_usec
1880 This is the fractional part of the last access time for the file.
1881 @xref{File Times}.
1883 @item time_t st_mtime
1884 This is the time of the last modification to the contents of the file.
1885 @xref{File Times}.
1887 @item unsigned long int st_mtime_usec
1888 This is the fractional part of the time of the last modification to the
1889 contents of the file.  @xref{File Times}.
1891 @item time_t st_ctime
1892 This is the time of the last modification to the attributes of the file.
1893 @xref{File Times}.
1895 @item unsigned long int st_ctime_usec
1896 This is the fractional part of the time of the last modification to the
1897 attributes of the file.  @xref{File Times}.
1899 @c !!! st_rdev
1900 @item blkcnt64_t st_blocks
1901 This is the amount of disk space that the file occupies, measured in
1902 units of 512-byte blocks.
1904 @item unsigned int st_blksize
1905 The optimal block size for reading of writing this file, in bytes.  You
1906 might use this size for allocating the buffer space for reading of
1907 writing the file.  (This is unrelated to @code{st_blocks}.)
1908 @end table
1909 @end deftp
1911 Some of the file attributes have special data type names which exist
1912 specifically for those attributes.  (They are all aliases for well-known
1913 integer types that you know and love.)  These typedef names are defined
1914 in the header file @file{sys/types.h} as well as in @file{sys/stat.h}.
1915 Here is a list of them.
1917 @deftp {Data Type} mode_t
1918 @standards{POSIX.1, sys/types.h}
1919 This is an integer data type used to represent file modes.  In
1920 @theglibc{}, this is an unsigned type no narrower than @code{unsigned
1921 int}.
1922 @end deftp
1924 @cindex inode number
1925 @deftp {Data Type} ino_t
1926 @standards{POSIX.1, sys/types.h}
1927 This is an unsigned integer type used to represent file serial numbers.
1928 (In Unix jargon, these are sometimes called @dfn{inode numbers}.)
1929 In @theglibc{}, this type is no narrower than @code{unsigned int}.
1931 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1932 is transparently replaced by @code{ino64_t}.
1933 @end deftp
1935 @deftp {Data Type} ino64_t
1936 @standards{Unix98, sys/types.h}
1937 This is an unsigned integer type used to represent file serial numbers
1938 for the use in LFS.  In @theglibc{}, this type is no narrower than
1939 @code{unsigned int}.
1941 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1942 available under the name @code{ino_t}.
1943 @end deftp
1945 @deftp {Data Type} dev_t
1946 @standards{POSIX.1, sys/types.h}
1947 This is an arithmetic data type used to represent file device numbers.
1948 In @theglibc{}, this is an integer type no narrower than @code{int}.
1949 @end deftp
1951 @deftp {Data Type} nlink_t
1952 @standards{POSIX.1, sys/types.h}
1953 This is an integer type used to represent file link counts.
1954 @end deftp
1956 @deftp {Data Type} blkcnt_t
1957 @standards{Unix98, sys/types.h}
1958 This is a signed integer type used to represent block counts.
1959 In @theglibc{}, this type is no narrower than @code{int}.
1961 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1962 is transparently replaced by @code{blkcnt64_t}.
1963 @end deftp
1965 @deftp {Data Type} blkcnt64_t
1966 @standards{Unix98, sys/types.h}
1967 This is a signed integer type used to represent block counts for the
1968 use in LFS.  In @theglibc{}, this type is no narrower than @code{int}.
1970 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1971 available under the name @code{blkcnt_t}.
1972 @end deftp
1974 @node Reading Attributes
1975 @subsection Reading the Attributes of a File
1977 To examine the attributes of files, use the functions @code{stat},
1978 @code{fstat} and @code{lstat}.  They return the attribute information in
1979 a @code{struct stat} object.  All three functions are declared in the
1980 header file @file{sys/stat.h}.
1982 @deftypefun int stat (const char *@var{filename}, struct stat *@var{buf})
1983 @standards{POSIX.1, sys/stat.h}
1984 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1985 The @code{stat} function returns information about the attributes of the
1986 file named by @w{@var{filename}} in the structure pointed to by @var{buf}.
1988 If @var{filename} is the name of a symbolic link, the attributes you get
1989 describe the file that the link points to.  If the link points to a
1990 nonexistent file name, then @code{stat} fails reporting a nonexistent
1991 file.
1993 The return value is @code{0} if the operation is successful, or
1994 @code{-1} on failure.  In addition to the usual file name errors
1995 (@pxref{File Name Errors}, the following @code{errno} error conditions
1996 are defined for this function:
1998 @table @code
1999 @item ENOENT
2000 The file named by @var{filename} doesn't exist.
2001 @end table
2003 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2004 function is in fact @code{stat64} since the LFS interface transparently
2005 replaces the normal implementation.
2006 @end deftypefun
2008 @deftypefun int stat64 (const char *@var{filename}, struct stat64 *@var{buf})
2009 @standards{Unix98, sys/stat.h}
2010 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2011 This function is similar to @code{stat} but it is also able to work on
2012 files larger than @twoexp{31} bytes on 32-bit systems.  To be able to do
2013 this the result is stored in a variable of type @code{struct stat64} to
2014 which @var{buf} must point.
2016 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2017 function is available under the name @code{stat} and so transparently
2018 replaces the interface for small files on 32-bit machines.
2019 @end deftypefun
2021 @deftypefun int fstat (int @var{filedes}, struct stat *@var{buf})
2022 @standards{POSIX.1, sys/stat.h}
2023 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2024 The @code{fstat} function is like @code{stat}, except that it takes an
2025 open file descriptor as an argument instead of a file name.
2026 @xref{Low-Level I/O}.
2028 Like @code{stat}, @code{fstat} returns @code{0} on success and @code{-1}
2029 on failure.  The following @code{errno} error conditions are defined for
2030 @code{fstat}:
2032 @table @code
2033 @item EBADF
2034 The @var{filedes} argument is not a valid file descriptor.
2035 @end table
2037 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2038 function is in fact @code{fstat64} since the LFS interface transparently
2039 replaces the normal implementation.
2040 @end deftypefun
2042 @deftypefun int fstat64 (int @var{filedes}, struct stat64 *@var{buf})
2043 @standards{Unix98, sys/stat.h}
2044 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2045 This function is similar to @code{fstat} but is able to work on large
2046 files on 32-bit platforms.  For large files the file descriptor
2047 @var{filedes} should be obtained by @code{open64} or @code{creat64}.
2048 The @var{buf} pointer points to a variable of type @code{struct stat64}
2049 which is able to represent the larger values.
2051 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2052 function is available under the name @code{fstat} and so transparently
2053 replaces the interface for small files on 32-bit machines.
2054 @end deftypefun
2056 @c fstatat will call alloca and snprintf if the syscall is not
2057 @c available.
2058 @c @safety{@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2060 @deftypefun int lstat (const char *@var{filename}, struct stat *@var{buf})
2061 @standards{BSD, sys/stat.h}
2062 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2063 @c Direct system call through lxstat, sometimes with an xstat conv call
2064 @c afterwards.
2065 The @code{lstat} function is like @code{stat}, except that it does not
2066 follow symbolic links.  If @var{filename} is the name of a symbolic
2067 link, @code{lstat} returns information about the link itself; otherwise
2068 @code{lstat} works like @code{stat}.  @xref{Symbolic Links}.
2070 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2071 function is in fact @code{lstat64} since the LFS interface transparently
2072 replaces the normal implementation.
2073 @end deftypefun
2075 @deftypefun int lstat64 (const char *@var{filename}, struct stat64 *@var{buf})
2076 @standards{Unix98, sys/stat.h}
2077 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2078 @c Direct system call through lxstat64, sometimes with an xstat conv
2079 @c call afterwards.
2080 This function is similar to @code{lstat} but it is also able to work on
2081 files larger than @twoexp{31} bytes on 32-bit systems.  To be able to do
2082 this the result is stored in a variable of type @code{struct stat64} to
2083 which @var{buf} must point.
2085 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2086 function is available under the name @code{lstat} and so transparently
2087 replaces the interface for small files on 32-bit machines.
2088 @end deftypefun
2090 @node Testing File Type
2091 @subsection Testing the Type of a File
2093 The @dfn{file mode}, stored in the @code{st_mode} field of the file
2094 attributes, contains two kinds of information: the file type code, and
2095 the access permission bits.  This section discusses only the type code,
2096 which you can use to tell whether the file is a directory, socket,
2097 symbolic link, and so on.  For details about access permissions see
2098 @ref{Permission Bits}.
2100 There are two ways you can access the file type information in a file
2101 mode.  Firstly, for each file type there is a @dfn{predicate macro}
2102 which examines a given file mode and returns whether it is of that type
2103 or not.  Secondly, you can mask out the rest of the file mode to leave
2104 just the file type code, and compare this against constants for each of
2105 the supported file types.
2107 All of the symbols listed in this section are defined in the header file
2108 @file{sys/stat.h}.
2109 @pindex sys/stat.h
2111 The following predicate macros test the type of a file, given the value
2112 @var{m} which is the @code{st_mode} field returned by @code{stat} on
2113 that file:
2115 @deftypefn Macro int S_ISDIR (mode_t @var{m})
2116 @standards{POSIX, sys/stat.h}
2117 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2118 This macro returns non-zero if the file is a directory.
2119 @end deftypefn
2121 @deftypefn Macro int S_ISCHR (mode_t @var{m})
2122 @standards{POSIX, sys/stat.h}
2123 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2124 This macro returns non-zero if the file is a character special file (a
2125 device like a terminal).
2126 @end deftypefn
2128 @deftypefn Macro int S_ISBLK (mode_t @var{m})
2129 @standards{POSIX, sys/stat.h}
2130 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2131 This macro returns non-zero if the file is a block special file (a device
2132 like a disk).
2133 @end deftypefn
2135 @deftypefn Macro int S_ISREG (mode_t @var{m})
2136 @standards{POSIX, sys/stat.h}
2137 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2138 This macro returns non-zero if the file is a regular file.
2139 @end deftypefn
2141 @deftypefn Macro int S_ISFIFO (mode_t @var{m})
2142 @standards{POSIX, sys/stat.h}
2143 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2144 This macro returns non-zero if the file is a FIFO special file, or a
2145 pipe.  @xref{Pipes and FIFOs}.
2146 @end deftypefn
2148 @deftypefn Macro int S_ISLNK (mode_t @var{m})
2149 @standards{GNU, sys/stat.h}
2150 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2151 This macro returns non-zero if the file is a symbolic link.
2152 @xref{Symbolic Links}.
2153 @end deftypefn
2155 @deftypefn Macro int S_ISSOCK (mode_t @var{m})
2156 @standards{GNU, sys/stat.h}
2157 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2158 This macro returns non-zero if the file is a socket.  @xref{Sockets}.
2159 @end deftypefn
2161 An alternate non-POSIX method of testing the file type is supported for
2162 compatibility with BSD.  The mode can be bitwise AND-ed with
2163 @code{S_IFMT} to extract the file type code, and compared to the
2164 appropriate constant.  For example,
2166 @smallexample
2167 S_ISCHR (@var{mode})
2168 @end smallexample
2170 @noindent
2171 is equivalent to:
2173 @smallexample
2174 ((@var{mode} & S_IFMT) == S_IFCHR)
2175 @end smallexample
2177 @deftypevr Macro int S_IFMT
2178 @standards{BSD, sys/stat.h}
2179 This is a bit mask used to extract the file type code from a mode value.
2180 @end deftypevr
2182 These are the symbolic names for the different file type codes:
2184 @vtable @code
2185 @item S_IFDIR
2186 @standards{BSD, sys/stat.h}
2187 This is the file type constant of a directory file.
2189 @item S_IFCHR
2190 @standards{BSD, sys/stat.h}
2191 This is the file type constant of a character-oriented device file.
2193 @item S_IFBLK
2194 @standards{BSD, sys/stat.h}
2195 This is the file type constant of a block-oriented device file.
2197 @item S_IFREG
2198 @standards{BSD, sys/stat.h}
2199 This is the file type constant of a regular file.
2201 @item S_IFLNK
2202 @standards{BSD, sys/stat.h}
2203 This is the file type constant of a symbolic link.
2205 @item S_IFSOCK
2206 @standards{BSD, sys/stat.h}
2207 This is the file type constant of a socket.
2209 @item S_IFIFO
2210 @standards{BSD, sys/stat.h}
2211 This is the file type constant of a FIFO or pipe.
2212 @end vtable
2214 The POSIX.1b standard introduced a few more objects which possibly can
2215 be implemented as objects in the filesystem.  These are message queues,
2216 semaphores, and shared memory objects.  To allow differentiating these
2217 objects from other files the POSIX standard introduced three new test
2218 macros.  But unlike the other macros they do not take the value of the
2219 @code{st_mode} field as the parameter.  Instead they expect a pointer to
2220 the whole @code{struct stat} structure.
2222 @deftypefn Macro int S_TYPEISMQ (struct stat *@var{s})
2223 @standards{POSIX, sys/stat.h}
2224 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2225 If the system implements POSIX message queues as distinct objects and the
2226 file is a message queue object, this macro returns a non-zero value.
2227 In all other cases the result is zero.
2228 @end deftypefn
2230 @deftypefn Macro int S_TYPEISSEM (struct stat *@var{s})
2231 @standards{POSIX, sys/stat.h}
2232 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2233 If the system implements POSIX semaphores as distinct objects and the
2234 file is a semaphore object, this macro returns a non-zero value.
2235 In all other cases the result is zero.
2236 @end deftypefn
2238 @deftypefn Macro int S_TYPEISSHM (struct stat *@var{s})
2239 @standards{POSIX, sys/stat.h}
2240 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2241 If the system implements POSIX shared memory objects as distinct objects
2242 and the file is a shared memory object, this macro returns a non-zero
2243 value.  In all other cases the result is zero.
2244 @end deftypefn
2246 @node File Owner
2247 @subsection File Owner
2248 @cindex file owner
2249 @cindex owner of a file
2250 @cindex group owner of a file
2252 Every file has an @dfn{owner} which is one of the registered user names
2253 defined on the system.  Each file also has a @dfn{group} which is one of
2254 the defined groups.  The file owner can often be useful for showing you
2255 who edited the file (especially when you edit with GNU Emacs), but its
2256 main purpose is for access control.
2258 The file owner and group play a role in determining access because the
2259 file has one set of access permission bits for the owner, another set
2260 that applies to users who belong to the file's group, and a third set of
2261 bits that applies to everyone else.  @xref{Access Permission}, for the
2262 details of how access is decided based on this data.
2264 When a file is created, its owner is set to the effective user ID of the
2265 process that creates it (@pxref{Process Persona}).  The file's group ID
2266 may be set to either the effective group ID of the process, or the group
2267 ID of the directory that contains the file, depending on the system
2268 where the file is stored.  When you access a remote file system, it
2269 behaves according to its own rules, not according to the system your
2270 program is running on.  Thus, your program must be prepared to encounter
2271 either kind of behavior no matter what kind of system you run it on.
2273 @pindex chown
2274 @pindex chgrp
2275 You can change the owner and/or group owner of an existing file using
2276 the @code{chown} function.  This is the primitive for the @code{chown}
2277 and @code{chgrp} shell commands.
2279 @pindex unistd.h
2280 The prototype for this function is declared in @file{unistd.h}.
2282 @deftypefun int chown (const char *@var{filename}, uid_t @var{owner}, gid_t @var{group})
2283 @standards{POSIX.1, unistd.h}
2284 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2285 The @code{chown} function changes the owner of the file @var{filename} to
2286 @var{owner}, and its group owner to @var{group}.
2288 Changing the owner of the file on certain systems clears the set-user-ID
2289 and set-group-ID permission bits.  (This is because those bits may not
2290 be appropriate for the new owner.)  Other file permission bits are not
2291 changed.
2293 The return value is @code{0} on success and @code{-1} on failure.
2294 In addition to the usual file name errors (@pxref{File Name Errors}),
2295 the following @code{errno} error conditions are defined for this function:
2297 @table @code
2298 @item EPERM
2299 This process lacks permission to make the requested change.
2301 Only privileged users or the file's owner can change the file's group.
2302 On most file systems, only privileged users can change the file owner;
2303 some file systems allow you to change the owner if you are currently the
2304 owner.  When you access a remote file system, the behavior you encounter
2305 is determined by the system that actually holds the file, not by the
2306 system your program is running on.
2308 @xref{Options for Files}, for information about the
2309 @code{_POSIX_CHOWN_RESTRICTED} macro.
2311 @item EROFS
2312 The file is on a read-only file system.
2313 @end table
2314 @end deftypefun
2316 @deftypefun int fchown (int @var{filedes}, uid_t @var{owner}, gid_t @var{group})
2317 @standards{BSD, unistd.h}
2318 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2319 This is like @code{chown}, except that it changes the owner of the open
2320 file with descriptor @var{filedes}.
2322 The return value from @code{fchown} is @code{0} on success and @code{-1}
2323 on failure.  The following @code{errno} error codes are defined for this
2324 function:
2326 @table @code
2327 @item EBADF
2328 The @var{filedes} argument is not a valid file descriptor.
2330 @item EINVAL
2331 The @var{filedes} argument corresponds to a pipe or socket, not an ordinary
2332 file.
2334 @item EPERM
2335 This process lacks permission to make the requested change.  For details
2336 see @code{chmod} above.
2338 @item EROFS
2339 The file resides on a read-only file system.
2340 @end table
2341 @end deftypefun
2343 @node Permission Bits
2344 @subsection The Mode Bits for Access Permission
2346 The @dfn{file mode}, stored in the @code{st_mode} field of the file
2347 attributes, contains two kinds of information: the file type code, and
2348 the access permission bits.  This section discusses only the access
2349 permission bits, which control who can read or write the file.
2350 @xref{Testing File Type}, for information about the file type code.
2352 All of the symbols listed in this section are defined in the header file
2353 @file{sys/stat.h}.
2354 @pindex sys/stat.h
2356 @cindex file permission bits
2357 These symbolic constants are defined for the file mode bits that control
2358 access permission for the file:
2360 @vtable @code
2361 @item S_IRUSR
2362 @itemx S_IREAD
2363 @standards{POSIX.1, sys/stat.h}
2364 @standardsx{S_IREAD, BSD, sys/stat.h}
2365 Read permission bit for the owner of the file.  On many systems this bit
2366 is 0400.  @code{S_IREAD} is an obsolete synonym provided for BSD
2367 compatibility.
2369 @item S_IWUSR
2370 @itemx S_IWRITE
2371 @standards{POSIX.1, sys/stat.h}
2372 @standardsx{S_IWRITE, BSD, sys/stat.h}
2373 Write permission bit for the owner of the file.  Usually 0200.
2374 @w{@code{S_IWRITE}} is an obsolete synonym provided for BSD compatibility.
2376 @item S_IXUSR
2377 @itemx S_IEXEC
2378 @standards{POSIX.1, sys/stat.h}
2379 @standardsx{S_IEXEC, BSD, sys/stat.h}
2380 Execute (for ordinary files) or search (for directories) permission bit
2381 for the owner of the file.  Usually 0100.  @code{S_IEXEC} is an obsolete
2382 synonym provided for BSD compatibility.
2384 @item S_IRWXU
2385 @standards{POSIX.1, sys/stat.h}
2386 This is equivalent to @samp{(S_IRUSR | S_IWUSR | S_IXUSR)}.
2388 @item S_IRGRP
2389 @standards{POSIX.1, sys/stat.h}
2390 Read permission bit for the group owner of the file.  Usually 040.
2392 @item S_IWGRP
2393 @standards{POSIX.1, sys/stat.h}
2394 Write permission bit for the group owner of the file.  Usually 020.
2396 @item S_IXGRP
2397 @standards{POSIX.1, sys/stat.h}
2398 Execute or search permission bit for the group owner of the file.
2399 Usually 010.
2401 @item S_IRWXG
2402 @standards{POSIX.1, sys/stat.h}
2403 This is equivalent to @samp{(S_IRGRP | S_IWGRP | S_IXGRP)}.
2405 @item S_IROTH
2406 @standards{POSIX.1, sys/stat.h}
2407 Read permission bit for other users.  Usually 04.
2409 @item S_IWOTH
2410 @standards{POSIX.1, sys/stat.h}
2411 Write permission bit for other users.  Usually 02.
2413 @item S_IXOTH
2414 @standards{POSIX.1, sys/stat.h}
2415 Execute or search permission bit for other users.  Usually 01.
2417 @item S_IRWXO
2418 @standards{POSIX.1, sys/stat.h}
2419 This is equivalent to @samp{(S_IROTH | S_IWOTH | S_IXOTH)}.
2421 @item S_ISUID
2422 @standards{POSIX, sys/stat.h}
2423 This is the set-user-ID on execute bit, usually 04000.
2424 @xref{How Change Persona}.
2426 @item S_ISGID
2427 @standards{POSIX, sys/stat.h}
2428 This is the set-group-ID on execute bit, usually 02000.
2429 @xref{How Change Persona}.
2431 @cindex sticky bit
2432 @item S_ISVTX
2433 @standards{BSD, sys/stat.h}
2434 This is the @dfn{sticky} bit, usually 01000.
2436 For a directory it gives permission to delete a file in that directory
2437 only if you own that file.  Ordinarily, a user can either delete all the
2438 files in a directory or cannot delete any of them (based on whether the
2439 user has write permission for the directory).  The same restriction
2440 applies---you must have both write permission for the directory and own
2441 the file you want to delete.  The one exception is that the owner of the
2442 directory can delete any file in the directory, no matter who owns it
2443 (provided the owner has given himself write permission for the
2444 directory).  This is commonly used for the @file{/tmp} directory, where
2445 anyone may create files but not delete files created by other users.
2447 Originally the sticky bit on an executable file modified the swapping
2448 policies of the system.  Normally, when a program terminated, its pages
2449 in core were immediately freed and reused.  If the sticky bit was set on
2450 the executable file, the system kept the pages in core for a while as if
2451 the program were still running.  This was advantageous for a program
2452 likely to be run many times in succession.  This usage is obsolete in
2453 modern systems.  When a program terminates, its pages always remain in
2454 core as long as there is no shortage of memory in the system.  When the
2455 program is next run, its pages will still be in core if no shortage
2456 arose since the last run.
2458 On some modern systems where the sticky bit has no useful meaning for an
2459 executable file, you cannot set the bit at all for a non-directory.
2460 If you try, @code{chmod} fails with @code{EFTYPE};
2461 @pxref{Setting Permissions}.
2463 Some systems (particularly SunOS) have yet another use for the sticky
2464 bit.  If the sticky bit is set on a file that is @emph{not} executable,
2465 it means the opposite: never cache the pages of this file at all.  The
2466 main use of this is for the files on an NFS server machine which are
2467 used as the swap area of diskless client machines.  The idea is that the
2468 pages of the file will be cached in the client's memory, so it is a
2469 waste of the server's memory to cache them a second time.  With this
2470 usage the sticky bit also implies that the filesystem may fail to record
2471 the file's modification time onto disk reliably (the idea being that
2472 no-one cares for a swap file).
2474 This bit is only available on BSD systems (and those derived from
2475 them).  Therefore one has to use the @code{_GNU_SOURCE} feature select
2476 macro, or not define any feature test macros, to get the definition
2477 (@pxref{Feature Test Macros}).
2478 @end vtable
2480 The actual bit values of the symbols are listed in the table above
2481 so you can decode file mode values when debugging your programs.
2482 These bit values are correct for most systems, but they are not
2483 guaranteed.
2485 @strong{Warning:} Writing explicit numbers for file permissions is bad
2486 practice.  Not only is it not portable, it also requires everyone who
2487 reads your program to remember what the bits mean.  To make your program
2488 clean use the symbolic names.
2490 @node Access Permission
2491 @subsection How Your Access to a File is Decided
2492 @cindex permission to access a file
2493 @cindex access permission for a file
2494 @cindex file access permission
2496 Recall that the operating system normally decides access permission for
2497 a file based on the effective user and group IDs of the process and its
2498 supplementary group IDs, together with the file's owner, group and
2499 permission bits.  These concepts are discussed in detail in @ref{Process
2500 Persona}.
2502 If the effective user ID of the process matches the owner user ID of the
2503 file, then permissions for read, write, and execute/search are
2504 controlled by the corresponding ``user'' (or ``owner'') bits.  Likewise,
2505 if any of the effective group ID or supplementary group IDs of the
2506 process matches the group owner ID of the file, then permissions are
2507 controlled by the ``group'' bits.  Otherwise, permissions are controlled
2508 by the ``other'' bits.
2510 Privileged users, like @samp{root}, can access any file regardless of
2511 its permission bits.  As a special case, for a file to be executable
2512 even by a privileged user, at least one of its execute bits must be set.
2514 @node Setting Permissions
2515 @subsection Assigning File Permissions
2517 @cindex file creation mask
2518 @cindex umask
2519 The primitive functions for creating files (for example, @code{open} or
2520 @code{mkdir}) take a @var{mode} argument, which specifies the file
2521 permissions to give the newly created file.  This mode is modified by
2522 the process's @dfn{file creation mask}, or @dfn{umask}, before it is
2523 used.
2525 The bits that are set in the file creation mask identify permissions
2526 that are always to be disabled for newly created files.  For example, if
2527 you set all the ``other'' access bits in the mask, then newly created
2528 files are not accessible at all to processes in the ``other'' category,
2529 even if the @var{mode} argument passed to the create function would
2530 permit such access.  In other words, the file creation mask is the
2531 complement of the ordinary access permissions you want to grant.
2533 Programs that create files typically specify a @var{mode} argument that
2534 includes all the permissions that make sense for the particular file.
2535 For an ordinary file, this is typically read and write permission for
2536 all classes of users.  These permissions are then restricted as
2537 specified by the individual user's own file creation mask.
2539 @findex chmod
2540 To change the permission of an existing file given its name, call
2541 @code{chmod}.  This function uses the specified permission bits and
2542 ignores the file creation mask.
2544 @pindex umask
2545 In normal use, the file creation mask is initialized by the user's login
2546 shell (using the @code{umask} shell command), and inherited by all
2547 subprocesses.  Application programs normally don't need to worry about
2548 the file creation mask.  It will automatically do what it is supposed to
2551 When your program needs to create a file and bypass the umask for its
2552 access permissions, the easiest way to do this is to use @code{fchmod}
2553 after opening the file, rather than changing the umask.  In fact,
2554 changing the umask is usually done only by shells.  They use the
2555 @code{umask} function.
2557 The functions in this section are declared in @file{sys/stat.h}.
2558 @pindex sys/stat.h
2560 @deftypefun mode_t umask (mode_t @var{mask})
2561 @standards{POSIX.1, sys/stat.h}
2562 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2563 The @code{umask} function sets the file creation mask of the current
2564 process to @var{mask}, and returns the previous value of the file
2565 creation mask.
2567 Here is an example showing how to read the mask with @code{umask}
2568 without changing it permanently:
2570 @smallexample
2571 mode_t
2572 read_umask (void)
2574   mode_t mask = umask (0);
2575   umask (mask);
2576   return mask;
2578 @end smallexample
2580 @noindent
2581 However, on @gnuhurdsystems{} it is better to use @code{getumask} if
2582 you just want to read the mask value, because it is reentrant.
2583 @end deftypefun
2585 @deftypefun mode_t getumask (void)
2586 @standards{GNU, sys/stat.h}
2587 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2588 Return the current value of the file creation mask for the current
2589 process.  This function is a GNU extension and is only available on
2590 @gnuhurdsystems{}.
2591 @end deftypefun
2593 @deftypefun int chmod (const char *@var{filename}, mode_t @var{mode})
2594 @standards{POSIX.1, sys/stat.h}
2595 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2596 The @code{chmod} function sets the access permission bits for the file
2597 named by @var{filename} to @var{mode}.
2599 If @var{filename} is a symbolic link, @code{chmod} changes the
2600 permissions of the file pointed to by the link, not those of the link
2601 itself.
2603 This function returns @code{0} if successful and @code{-1} if not.  In
2604 addition to the usual file name errors (@pxref{File Name
2605 Errors}), the following @code{errno} error conditions are defined for
2606 this function:
2608 @table @code
2609 @item ENOENT
2610 The named file doesn't exist.
2612 @item EPERM
2613 This process does not have permission to change the access permissions
2614 of this file.  Only the file's owner (as judged by the effective user ID
2615 of the process) or a privileged user can change them.
2617 @item EROFS
2618 The file resides on a read-only file system.
2620 @item EFTYPE
2621 @var{mode} has the @code{S_ISVTX} bit (the ``sticky bit'') set,
2622 and the named file is not a directory.  Some systems do not allow setting the
2623 sticky bit on non-directory files, and some do (and only some of those
2624 assign a useful meaning to the bit for non-directory files).
2626 You only get @code{EFTYPE} on systems where the sticky bit has no useful
2627 meaning for non-directory files, so it is always safe to just clear the
2628 bit in @var{mode} and call @code{chmod} again.  @xref{Permission Bits},
2629 for full details on the sticky bit.
2630 @end table
2631 @end deftypefun
2633 @deftypefun int fchmod (int @var{filedes}, mode_t @var{mode})
2634 @standards{BSD, sys/stat.h}
2635 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2636 This is like @code{chmod}, except that it changes the permissions of the
2637 currently open file given by @var{filedes}.
2639 The return value from @code{fchmod} is @code{0} on success and @code{-1}
2640 on failure.  The following @code{errno} error codes are defined for this
2641 function:
2643 @table @code
2644 @item EBADF
2645 The @var{filedes} argument is not a valid file descriptor.
2647 @item EINVAL
2648 The @var{filedes} argument corresponds to a pipe or socket, or something
2649 else that doesn't really have access permissions.
2651 @item EPERM
2652 This process does not have permission to change the access permissions
2653 of this file.  Only the file's owner (as judged by the effective user ID
2654 of the process) or a privileged user can change them.
2656 @item EROFS
2657 The file resides on a read-only file system.
2658 @end table
2659 @end deftypefun
2661 @node Testing File Access
2662 @subsection Testing Permission to Access a File
2663 @cindex testing access permission
2664 @cindex access, testing for
2665 @cindex setuid programs and file access
2667 In some situations it is desirable to allow programs to access files or
2668 devices even if this is not possible with the permissions granted to the
2669 user.  One possible solution is to set the setuid-bit of the program
2670 file.  If such a program is started the @emph{effective} user ID of the
2671 process is changed to that of the owner of the program file.  So to
2672 allow write access to files like @file{/etc/passwd}, which normally can
2673 be written only by the super-user, the modifying program will have to be
2674 owned by @code{root} and the setuid-bit must be set.
2676 But besides the files the program is intended to change the user should
2677 not be allowed to access any file to which s/he would not have access
2678 anyway.  The program therefore must explicitly check whether @emph{the
2679 user} would have the necessary access to a file, before it reads or
2680 writes the file.
2682 To do this, use the function @code{access}, which checks for access
2683 permission based on the process's @emph{real} user ID rather than the
2684 effective user ID.  (The setuid feature does not alter the real user ID,
2685 so it reflects the user who actually ran the program.)
2687 There is another way you could check this access, which is easy to
2688 describe, but very hard to use.  This is to examine the file mode bits
2689 and mimic the system's own access computation.  This method is
2690 undesirable because many systems have additional access control
2691 features; your program cannot portably mimic them, and you would not
2692 want to try to keep track of the diverse features that different systems
2693 have.  Using @code{access} is simple and automatically does whatever is
2694 appropriate for the system you are using.
2696 @code{access} is @emph{only} appropriate to use in setuid programs.
2697 A non-setuid program will always use the effective ID rather than the
2698 real ID.
2700 @pindex unistd.h
2701 The symbols in this section are declared in @file{unistd.h}.
2703 @deftypefun int access (const char *@var{filename}, int @var{how})
2704 @standards{POSIX.1, unistd.h}
2705 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2706 The @code{access} function checks to see whether the file named by
2707 @var{filename} can be accessed in the way specified by the @var{how}
2708 argument.  The @var{how} argument either can be the bitwise OR of the
2709 flags @code{R_OK}, @code{W_OK}, @code{X_OK}, or the existence test
2710 @code{F_OK}.
2712 This function uses the @emph{real} user and group IDs of the calling
2713 process, rather than the @emph{effective} IDs, to check for access
2714 permission.  As a result, if you use the function from a @code{setuid}
2715 or @code{setgid} program (@pxref{How Change Persona}), it gives
2716 information relative to the user who actually ran the program.
2718 The return value is @code{0} if the access is permitted, and @code{-1}
2719 otherwise.  (In other words, treated as a predicate function,
2720 @code{access} returns true if the requested access is @emph{denied}.)
2722 In addition to the usual file name errors (@pxref{File Name
2723 Errors}), the following @code{errno} error conditions are defined for
2724 this function:
2726 @table @code
2727 @item EACCES
2728 The access specified by @var{how} is denied.
2730 @item ENOENT
2731 The file doesn't exist.
2733 @item EROFS
2734 Write permission was requested for a file on a read-only file system.
2735 @end table
2736 @end deftypefun
2738 These macros are defined in the header file @file{unistd.h} for use
2739 as the @var{how} argument to the @code{access} function.  The values
2740 are integer constants.
2741 @pindex unistd.h
2743 @deftypevr Macro int R_OK
2744 @standards{POSIX.1, unistd.h}
2745 Flag meaning test for read permission.
2746 @end deftypevr
2748 @deftypevr Macro int W_OK
2749 @standards{POSIX.1, unistd.h}
2750 Flag meaning test for write permission.
2751 @end deftypevr
2753 @deftypevr Macro int X_OK
2754 @standards{POSIX.1, unistd.h}
2755 Flag meaning test for execute/search permission.
2756 @end deftypevr
2758 @deftypevr Macro int F_OK
2759 @standards{POSIX.1, unistd.h}
2760 Flag meaning test for existence of the file.
2761 @end deftypevr
2763 @node File Times
2764 @subsection File Times
2766 @cindex file access time
2767 @cindex file modification time
2768 @cindex file attribute modification time
2769 Each file has three time stamps associated with it:  its access time,
2770 its modification time, and its attribute modification time.  These
2771 correspond to the @code{st_atime}, @code{st_mtime}, and @code{st_ctime}
2772 members of the @code{stat} structure; see @ref{File Attributes}.
2774 All of these times are represented in calendar time format, as
2775 @code{time_t} objects.  This data type is defined in @file{time.h}.
2776 For more information about representation and manipulation of time
2777 values, see @ref{Calendar Time}.
2778 @pindex time.h
2780 Reading from a file updates its access time attribute, and writing
2781 updates its modification time.  When a file is created, all three
2782 time stamps for that file are set to the current time.  In addition, the
2783 attribute change time and modification time fields of the directory that
2784 contains the new entry are updated.
2786 Adding a new name for a file with the @code{link} function updates the
2787 attribute change time field of the file being linked, and both the
2788 attribute change time and modification time fields of the directory
2789 containing the new name.  These same fields are affected if a file name
2790 is deleted with @code{unlink}, @code{remove} or @code{rmdir}.  Renaming
2791 a file with @code{rename} affects only the attribute change time and
2792 modification time fields of the two parent directories involved, and not
2793 the times for the file being renamed.
2795 Changing the attributes of a file (for example, with @code{chmod})
2796 updates its attribute change time field.
2798 You can also change some of the time stamps of a file explicitly using
2799 the @code{utime} function---all except the attribute change time.  You
2800 need to include the header file @file{utime.h} to use this facility.
2801 @pindex utime.h
2803 @deftp {Data Type} {struct utimbuf}
2804 @standards{POSIX.1, utime.h}
2805 The @code{utimbuf} structure is used with the @code{utime} function to
2806 specify new access and modification times for a file.  It contains the
2807 following members:
2809 @table @code
2810 @item time_t actime
2811 This is the access time for the file.
2813 @item time_t modtime
2814 This is the modification time for the file.
2815 @end table
2816 @end deftp
2818 @deftypefun int utime (const char *@var{filename}, const struct utimbuf *@var{times})
2819 @standards{POSIX.1, utime.h}
2820 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2821 @c In the absence of a utime syscall, it non-atomically converts times
2822 @c to a struct timeval and calls utimes.
2823 This function is used to modify the file times associated with the file
2824 named @var{filename}.
2826 If @var{times} is a null pointer, then the access and modification times
2827 of the file are set to the current time.  Otherwise, they are set to the
2828 values from the @code{actime} and @code{modtime} members (respectively)
2829 of the @code{utimbuf} structure pointed to by @var{times}.
2831 The attribute modification time for the file is set to the current time
2832 in either case (since changing the time stamps is itself a modification
2833 of the file attributes).
2835 The @code{utime} function returns @code{0} if successful and @code{-1}
2836 on failure.  In addition to the usual file name errors
2837 (@pxref{File Name Errors}), the following @code{errno} error conditions
2838 are defined for this function:
2840 @table @code
2841 @item EACCES
2842 There is a permission problem in the case where a null pointer was
2843 passed as the @var{times} argument.  In order to update the time stamp on
2844 the file, you must either be the owner of the file, have write
2845 permission for the file, or be a privileged user.
2847 @item ENOENT
2848 The file doesn't exist.
2850 @item EPERM
2851 If the @var{times} argument is not a null pointer, you must either be
2852 the owner of the file or be a privileged user.
2854 @item EROFS
2855 The file lives on a read-only file system.
2856 @end table
2857 @end deftypefun
2859 Each of the three time stamps has a corresponding microsecond part,
2860 which extends its resolution.  These fields are called
2861 @code{st_atime_usec}, @code{st_mtime_usec}, and @code{st_ctime_usec};
2862 each has a value between 0 and 999,999, which indicates the time in
2863 microseconds.  They correspond to the @code{tv_usec} field of a
2864 @code{timeval} structure; see @ref{High-Resolution Calendar}.
2866 The @code{utimes} function is like @code{utime}, but also lets you specify
2867 the fractional part of the file times.  The prototype for this function is
2868 in the header file @file{sys/time.h}.
2869 @pindex sys/time.h
2871 @deftypefun int utimes (const char *@var{filename}, const struct timeval @var{tvp}@t{[2]})
2872 @standards{BSD, sys/time.h}
2873 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2874 @c In the absence of a utimes syscall, it non-atomically converts tvp
2875 @c to struct timespec array and issues a utimensat syscall, or to
2876 @c struct utimbuf and calls utime.
2877 This function sets the file access and modification times of the file
2878 @var{filename}.  The new file access time is specified by
2879 @code{@var{tvp}[0]}, and the new modification time by
2880 @code{@var{tvp}[1]}.  Similar to @code{utime}, if @var{tvp} is a null
2881 pointer then the access and modification times of the file are set to
2882 the current time.  This function comes from BSD.
2884 The return values and error conditions are the same as for the @code{utime}
2885 function.
2886 @end deftypefun
2888 @deftypefun int lutimes (const char *@var{filename}, const struct timeval @var{tvp}@t{[2]})
2889 @standards{BSD, sys/time.h}
2890 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2891 @c Since there's no lutimes syscall, it non-atomically converts tvp
2892 @c to struct timespec array and issues a utimensat syscall.
2893 This function is like @code{utimes}, except that it does not follow
2894 symbolic links.  If @var{filename} is the name of a symbolic link,
2895 @code{lutimes} sets the file access and modification times of the
2896 symbolic link special file itself (as seen by @code{lstat};
2897 @pxref{Symbolic Links}) while @code{utimes} sets the file access and
2898 modification times of the file the symbolic link refers to.  This
2899 function comes from FreeBSD, and is not available on all platforms (if
2900 not available, it will fail with @code{ENOSYS}).
2902 The return values and error conditions are the same as for the @code{utime}
2903 function.
2904 @end deftypefun
2906 @deftypefun int futimes (int @var{fd}, const struct timeval @var{tvp}@t{[2]})
2907 @standards{BSD, sys/time.h}
2908 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2909 @c Since there's no futimes syscall, it non-atomically converts tvp
2910 @c to struct timespec array and issues a utimensat syscall, falling back
2911 @c to utimes on a /proc/self/fd symlink.
2912 This function is like @code{utimes}, except that it takes an open file
2913 descriptor as an argument instead of a file name.  @xref{Low-Level
2914 I/O}.  This function comes from FreeBSD, and is not available on all
2915 platforms (if not available, it will fail with @code{ENOSYS}).
2917 Like @code{utimes}, @code{futimes} returns @code{0} on success and @code{-1}
2918 on failure.  The following @code{errno} error conditions are defined for
2919 @code{futimes}:
2921 @table @code
2922 @item EACCES
2923 There is a permission problem in the case where a null pointer was
2924 passed as the @var{times} argument.  In order to update the time stamp on
2925 the file, you must either be the owner of the file, have write
2926 permission for the file, or be a privileged user.
2928 @item EBADF
2929 The @var{filedes} argument is not a valid file descriptor.
2931 @item EPERM
2932 If the @var{times} argument is not a null pointer, you must either be
2933 the owner of the file or be a privileged user.
2935 @item EROFS
2936 The file lives on a read-only file system.
2937 @end table
2938 @end deftypefun
2940 @node File Size
2941 @subsection File Size
2943 Normally file sizes are maintained automatically.  A file begins with a
2944 size of @math{0} and is automatically extended when data is written past
2945 its end.  It is also possible to empty a file completely by an
2946 @code{open} or @code{fopen} call.
2948 However, sometimes it is necessary to @emph{reduce} the size of a file.
2949 This can be done with the @code{truncate} and @code{ftruncate} functions.
2950 They were introduced in BSD Unix.  @code{ftruncate} was later added to
2951 POSIX.1.
2953 Some systems allow you to extend a file (creating holes) with these
2954 functions.  This is useful when using memory-mapped I/O
2955 (@pxref{Memory-mapped I/O}), where files are not automatically extended.
2956 However, it is not portable but must be implemented if @code{mmap}
2957 allows mapping of files (i.e., @code{_POSIX_MAPPED_FILES} is defined).
2959 Using these functions on anything other than a regular file gives
2960 @emph{undefined} results.  On many systems, such a call will appear to
2961 succeed, without actually accomplishing anything.
2963 @deftypefun int truncate (const char *@var{filename}, off_t @var{length})
2964 @standards{X/Open, unistd.h}
2965 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2966 @c In the absence of a truncate syscall, we use open and ftruncate.
2968 The @code{truncate} function changes the size of @var{filename} to
2969 @var{length}.  If @var{length} is shorter than the previous length, data
2970 at the end will be lost.  The file must be writable by the user to
2971 perform this operation.
2973 If @var{length} is longer, holes will be added to the end.  However, some
2974 systems do not support this feature and will leave the file unchanged.
2976 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
2977 @code{truncate} function is in fact @code{truncate64} and the type
2978 @code{off_t} has 64 bits which makes it possible to handle files up to
2979 @twoexp{63} bytes in length.
2981 The return value is @math{0} for success, or @math{-1} for an error.  In
2982 addition to the usual file name errors, the following errors may occur:
2984 @table @code
2986 @item EACCES
2987 The file is a directory or not writable.
2989 @item EINVAL
2990 @var{length} is negative.
2992 @item EFBIG
2993 The operation would extend the file beyond the limits of the operating system.
2995 @item EIO
2996 A hardware I/O error occurred.
2998 @item EPERM
2999 The file is "append-only" or "immutable".
3001 @item EINTR
3002 The operation was interrupted by a signal.
3004 @end table
3006 @end deftypefun
3008 @deftypefun int truncate64 (const char *@var{name}, off64_t @var{length})
3009 @standards{Unix98, unistd.h}
3010 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3011 @c In the absence of a syscall, try truncate if length fits.
3012 This function is similar to the @code{truncate} function.  The
3013 difference is that the @var{length} argument is 64 bits wide even on 32
3014 bits machines, which allows the handling of files with sizes up to
3015 @twoexp{63} bytes.
3017 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
3018 32 bits machine this function is actually available under the name
3019 @code{truncate} and so transparently replaces the 32 bits interface.
3020 @end deftypefun
3022 @deftypefun int ftruncate (int @var{fd}, off_t @var{length})
3023 @standards{POSIX, unistd.h}
3024 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3026 This is like @code{truncate}, but it works on a file descriptor @var{fd}
3027 for an opened file instead of a file name to identify the object.  The
3028 file must be opened for writing to successfully carry out the operation.
3030 The POSIX standard leaves it implementation defined what happens if the
3031 specified new @var{length} of the file is bigger than the original size.
3032 The @code{ftruncate} function might simply leave the file alone and do
3033 nothing or it can increase the size to the desired size.  In this later
3034 case the extended area should be zero-filled.  So using @code{ftruncate}
3035 is no reliable way to increase the file size but if it is possible it is
3036 probably the fastest way.  The function also operates on POSIX shared
3037 memory segments if these are implemented by the system.
3039 @code{ftruncate} is especially useful in combination with @code{mmap}.
3040 Since the mapped region must have a fixed size one cannot enlarge the
3041 file by writing something beyond the last mapped page.  Instead one has
3042 to enlarge the file itself and then remap the file with the new size.
3043 The example below shows how this works.
3045 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
3046 @code{ftruncate} function is in fact @code{ftruncate64} and the type
3047 @code{off_t} has 64 bits which makes it possible to handle files up to
3048 @twoexp{63} bytes in length.
3050 The return value is @math{0} for success, or @math{-1} for an error.  The
3051 following errors may occur:
3053 @table @code
3055 @item EBADF
3056 @var{fd} does not correspond to an open file.
3058 @item EACCES
3059 @var{fd} is a directory or not open for writing.
3061 @item EINVAL
3062 @var{length} is negative.
3064 @item EFBIG
3065 The operation would extend the file beyond the limits of the operating system.
3066 @c or the open() call -- with the not-yet-discussed feature of opening
3067 @c files with extra-large offsets.
3069 @item EIO
3070 A hardware I/O error occurred.
3072 @item EPERM
3073 The file is "append-only" or "immutable".
3075 @item EINTR
3076 The operation was interrupted by a signal.
3078 @c ENOENT is also possible on Linux --- however it only occurs if the file
3079 @c descriptor has a `file' structure but no `inode' structure.  I'm not
3080 @c sure how such an fd could be created.  Perhaps it's a bug.
3082 @end table
3084 @end deftypefun
3086 @deftypefun int ftruncate64 (int @var{id}, off64_t @var{length})
3087 @standards{Unix98, unistd.h}
3088 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3089 @c In the absence of a syscall, try ftruncate if length fits.
3090 This function is similar to the @code{ftruncate} function.  The
3091 difference is that the @var{length} argument is 64 bits wide even on 32
3092 bits machines which allows the handling of files with sizes up to
3093 @twoexp{63} bytes.
3095 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
3096 32 bits machine this function is actually available under the name
3097 @code{ftruncate} and so transparently replaces the 32 bits interface.
3098 @end deftypefun
3100 As announced here is a little example of how to use @code{ftruncate} in
3101 combination with @code{mmap}:
3103 @smallexample
3104 int fd;
3105 void *start;
3106 size_t len;
3109 add (off_t at, void *block, size_t size)
3111   if (at + size > len)
3112     @{
3113       /* Resize the file and remap.  */
3114       size_t ps = sysconf (_SC_PAGESIZE);
3115       size_t ns = (at + size + ps - 1) & ~(ps - 1);
3116       void *np;
3117       if (ftruncate (fd, ns) < 0)
3118         return -1;
3119       np = mmap (NULL, ns, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
3120       if (np == MAP_FAILED)
3121         return -1;
3122       start = np;
3123       len = ns;
3124     @}
3125   memcpy ((char *) start + at, block, size);
3126   return 0;
3128 @end smallexample
3130 The function @code{add} writes a block of memory at an arbitrary
3131 position in the file.  If the current size of the file is too small it
3132 is extended.  Note that it is extended by a whole number of pages.  This
3133 is a requirement of @code{mmap}.  The program has to keep track of the
3134 real size, and when it has finished a final @code{ftruncate} call should
3135 set the real size of the file.
3137 @node Storage Allocation
3138 @subsection Storage Allocation
3139 @cindex allocating file storage
3140 @cindex file allocation
3141 @cindex storage allocating
3143 @cindex file fragmentation
3144 @cindex fragmentation of files
3145 @cindex sparse files
3146 @cindex files, sparse
3147 Most file systems support allocating large files in a non-contiguous
3148 fashion: the file is split into @emph{fragments} which are allocated
3149 sequentially, but the fragments themselves can be scattered across the
3150 disk.  File systems generally try to avoid such fragmentation because it
3151 decreases performance, but if a file gradually increases in size, there
3152 might be no other option than to fragment it.  In addition, many file
3153 systems support @emph{sparse files} with @emph{holes}: regions of null
3154 bytes for which no backing storage has been allocated by the file
3155 system.  When the holes are finally overwritten with data, fragmentation
3156 can occur as well.
3158 Explicit allocation of storage for yet-unwritten parts of the file can
3159 help the system to avoid fragmentation.  Additionally, if storage
3160 pre-allocation fails, it is possible to report the out-of-disk error
3161 early, often without filling up the entire disk.  However, due to
3162 deduplication, copy-on-write semantics, and file compression, such
3163 pre-allocation may not reliably prevent the out-of-disk-space error from
3164 occurring later.  Checking for write errors is still required, and
3165 writes to memory-mapped regions created with @code{mmap} can still
3166 result in @code{SIGBUS}.
3168 @deftypefun int posix_fallocate (int @var{fd}, off_t @var{offset}, off_t @var{length})
3169 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3170 @c If the file system does not support allocation,
3171 @c @code{posix_fallocate} has a race with file extension (if
3172 @c @var{length} is zero) or with concurrent writes of non-NUL bytes (if
3173 @c @var{length} is positive).
3175 Allocate backing store for the region of @var{length} bytes starting at
3176 byte @var{offset} in the file for the descriptor @var{fd}.  The file
3177 length is increased to @samp{@var{length} + @var{offset}} if necessary.
3179 @var{fd} must be a regular file opened for writing, or @code{EBADF} is
3180 returned.  If there is insufficient disk space to fulfill the allocation
3181 request, @code{ENOSPC} is returned.
3183 @strong{Note:} If @code{fallocate} is not available (because the file
3184 system does not support it), @code{posix_fallocate} is emulated, which
3185 has the following drawbacks:
3187 @itemize @bullet
3188 @item
3189 It is very inefficient because all file system blocks in the requested
3190 range need to be examined (even if they have been allocated before) and
3191 potentially rewritten.  In contrast, with proper @code{fallocate}
3192 support (see below), the file system can examine the internal file
3193 allocation data structures and eliminate holes directly, maybe even
3194 using unwritten extents (which are pre-allocated but uninitialized on
3195 disk).
3197 @item
3198 There is a race condition if another thread or process modifies the
3199 underlying file in the to-be-allocated area.  Non-null bytes could be
3200 overwritten with null bytes.
3202 @item
3203 If @var{fd} has been opened with the @code{O_WRONLY} flag, the function
3204 will fail with an @code{errno} value of @code{EBADF}.
3206 @item
3207 If @var{fd} has been opened with the @code{O_APPEND} flag, the function
3208 will fail with an @code{errno} value of @code{EBADF}.
3210 @item
3211 If @var{length} is zero, @code{ftruncate} is used to increase the file
3212 size as requested, without allocating file system blocks.  There is a
3213 race condition which means that @code{ftruncate} can accidentally
3214 truncate the file if it has been extended concurrently.
3215 @end itemize
3217 On Linux, if an application does not benefit from emulation or if the
3218 emulation is harmful due to its inherent race conditions, the
3219 application can use the Linux-specific @code{fallocate} function, with a
3220 zero flag argument.  For the @code{fallocate} function, @theglibc{} does
3221 not perform allocation emulation if the file system does not support
3222 allocation.  Instead, an @code{EOPNOTSUPP} is returned to the caller.
3224 @end deftypefun
3226 @deftypefun int posix_fallocate64 (int @var{fd}, off64_t @var{offset}, off64_t @var{length})
3227 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3229 This function is a variant of @code{posix_fallocate64} which accepts
3230 64-bit file offsets on all platforms.
3232 @end deftypefun
3234 @node Making Special Files
3235 @section Making Special Files
3236 @cindex creating special files
3237 @cindex special files
3239 The @code{mknod} function is the primitive for making special files,
3240 such as files that correspond to devices.  @Theglibc{} includes
3241 this function for compatibility with BSD.
3243 The prototype for @code{mknod} is declared in @file{sys/stat.h}.
3244 @pindex sys/stat.h
3246 @deftypefun int mknod (const char *@var{filename}, mode_t @var{mode}, dev_t @var{dev})
3247 @standards{BSD, sys/stat.h}
3248 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3249 @c Instead of issuing the syscall directly, we go through xmknod.
3250 @c Although the internal xmknod takes a dev_t*, that could lead to
3251 @c @mtsrace races, it's passed a pointer to mknod's dev.
3252 The @code{mknod} function makes a special file with name @var{filename}.
3253 The @var{mode} specifies the mode of the file, and may include the various
3254 special file bits, such as @code{S_IFCHR} (for a character special file)
3255 or @code{S_IFBLK} (for a block special file).  @xref{Testing File Type}.
3257 The @var{dev} argument specifies which device the special file refers to.
3258 Its exact interpretation depends on the kind of special file being created.
3260 The return value is @code{0} on success and @code{-1} on error.  In addition
3261 to the usual file name errors (@pxref{File Name Errors}), the
3262 following @code{errno} error conditions are defined for this function:
3264 @table @code
3265 @item EPERM
3266 The calling process is not privileged.  Only the superuser can create
3267 special files.
3269 @item ENOSPC
3270 The directory or file system that would contain the new file is full
3271 and cannot be extended.
3273 @item EROFS
3274 The directory containing the new file can't be modified because it's on
3275 a read-only file system.
3277 @item EEXIST
3278 There is already a file named @var{filename}.  If you want to replace
3279 this file, you must remove the old file explicitly first.
3280 @end table
3281 @end deftypefun
3283 @node Temporary Files
3284 @section Temporary Files
3286 If you need to use a temporary file in your program, you can use the
3287 @code{tmpfile} function to open it.  Or you can use the @code{tmpnam}
3288 (better: @code{tmpnam_r}) function to provide a name for a temporary
3289 file and then you can open it in the usual way with @code{fopen}.
3291 The @code{tempnam} function is like @code{tmpnam} but lets you choose
3292 what directory temporary files will go in, and something about what
3293 their file names will look like.  Important for multi-threaded programs
3294 is that @code{tempnam} is reentrant, while @code{tmpnam} is not since it
3295 returns a pointer to a static buffer.
3297 These facilities are declared in the header file @file{stdio.h}.
3298 @pindex stdio.h
3300 @deftypefun {FILE *} tmpfile (void)
3301 @standards{ISO, stdio.h}
3302 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @acsfd{} @aculock{}}}
3303 @c The unsafety issues are those of fdopen, plus @acsfd because of the
3304 @c open.
3305 @c __path_search (internal buf, !dir, const pfx, !try_tmpdir) ok
3306 @c  libc_secure_genenv only if try_tmpdir
3307 @c  xstat64, strlen, strcmp, sprintf
3308 @c __gen_tempname (internal tmpl, __GT_FILE) ok
3309 @c  strlen, memcmp, getpid, open/mkdir/lxstat64 ok
3310 @c  HP_TIMING_NOW if available ok
3311 @c  gettimeofday (!tz) first time, or every time if no HP_TIMING_NOW ok
3312 @c  static value is used and modified without synchronization ok
3313 @c   but the use is as a source of non-cryptographic randomness
3314 @c   with retries in case of collision, so it should be safe
3315 @c unlink, fdopen
3316 This function creates a temporary binary file for update mode, as if by
3317 calling @code{fopen} with mode @code{"wb+"}.  The file is deleted
3318 automatically when it is closed or when the program terminates.  (On
3319 some other @w{ISO C} systems the file may fail to be deleted if the program
3320 terminates abnormally).
3322 This function is reentrant.
3324 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
3325 32-bit system this function is in fact @code{tmpfile64}, i.e., the LFS
3326 interface transparently replaces the old interface.
3327 @end deftypefun
3329 @deftypefun {FILE *} tmpfile64 (void)
3330 @standards{Unix98, stdio.h}
3331 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @acsfd{} @aculock{}}}
3332 This function is similar to @code{tmpfile}, but the stream it returns a
3333 pointer to was opened using @code{tmpfile64}.  Therefore this stream can
3334 be used for files larger than @twoexp{31} bytes on 32-bit machines.
3336 Please note that the return type is still @code{FILE *}.  There is no
3337 special @code{FILE} type for the LFS interface.
3339 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
3340 bits machine this function is available under the name @code{tmpfile}
3341 and so transparently replaces the old interface.
3342 @end deftypefun
3344 @deftypefun {char *} tmpnam (char *@var{result})
3345 @standards{ISO, stdio.h}
3346 @safety{@prelim{}@mtunsafe{@mtasurace{:tmpnam/!result}}@asunsafe{}@acsafe{}}
3347 @c The passed-in buffer should not be modified concurrently with the
3348 @c call.
3349 @c __path_search (static or passed-in buf, !dir, !pfx, !try_tmpdir) ok
3350 @c __gen_tempname (internal tmpl, __GT_NOCREATE) ok
3351 This function constructs and returns a valid file name that does not
3352 refer to any existing file.  If the @var{result} argument is a null
3353 pointer, the return value is a pointer to an internal static string,
3354 which might be modified by subsequent calls and therefore makes this
3355 function non-reentrant.  Otherwise, the @var{result} argument should be
3356 a pointer to an array of at least @code{L_tmpnam} characters, and the
3357 result is written into that array.
3359 It is possible for @code{tmpnam} to fail if you call it too many times
3360 without removing previously-created files.  This is because the limited
3361 length of the temporary file names gives room for only a finite number
3362 of different names.  If @code{tmpnam} fails it returns a null pointer.
3364 @strong{Warning:} Between the time the pathname is constructed and the
3365 file is created another process might have created a file with the same
3366 name using @code{tmpnam}, leading to a possible security hole.  The
3367 implementation generates names which can hardly be predicted, but when
3368 opening the file you should use the @code{O_EXCL} flag.  Using
3369 @code{tmpfile} or @code{mkstemp} is a safe way to avoid this problem.
3370 @end deftypefun
3372 @deftypefun {char *} tmpnam_r (char *@var{result})
3373 @standards{GNU, stdio.h}
3374 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3375 This function is nearly identical to the @code{tmpnam} function, except
3376 that if @var{result} is a null pointer it returns a null pointer.
3378 This guarantees reentrancy because the non-reentrant situation of
3379 @code{tmpnam} cannot happen here.
3381 @strong{Warning}: This function has the same security problems as
3382 @code{tmpnam}.
3383 @end deftypefun
3385 @deftypevr Macro int L_tmpnam
3386 @standards{ISO, stdio.h}
3387 The value of this macro is an integer constant expression that
3388 represents the minimum size of a string large enough to hold a file name
3389 generated by the @code{tmpnam} function.
3390 @end deftypevr
3392 @deftypevr Macro int TMP_MAX
3393 @standards{ISO, stdio.h}
3394 The macro @code{TMP_MAX} is a lower bound for how many temporary names
3395 you can create with @code{tmpnam}.  You can rely on being able to call
3396 @code{tmpnam} at least this many times before it might fail saying you
3397 have made too many temporary file names.
3399 With @theglibc{}, you can create a very large number of temporary
3400 file names.  If you actually created the files, you would probably run
3401 out of disk space before you ran out of names.  Some other systems have
3402 a fixed, small limit on the number of temporary files.  The limit is
3403 never less than @code{25}.
3404 @end deftypevr
3406 @deftypefun {char *} tempnam (const char *@var{dir}, const char *@var{prefix})
3407 @standards{SVID, stdio.h}
3408 @safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
3409 @c There's no way (short of being setuid) to avoid getenv("TMPDIR"),
3410 @c even with a non-NULL dir.
3412 @c __path_search (internal buf, dir, pfx, try_tmpdir) unsafe getenv
3413 @c __gen_tempname (internal tmpl, __GT_NOCREATE) ok
3414 @c strdup
3415 This function generates a unique temporary file name.  If @var{prefix}
3416 is not a null pointer, up to five characters of this string are used as
3417 a prefix for the file name.  The return value is a string newly
3418 allocated with @code{malloc}, so you should release its storage with
3419 @code{free} when it is no longer needed.
3421 Because the string is dynamically allocated this function is reentrant.
3423 The directory prefix for the temporary file name is determined by
3424 testing each of the following in sequence.  The directory must exist and
3425 be writable.
3427 @itemize @bullet
3428 @item
3429 The environment variable @code{TMPDIR}, if it is defined.  For security
3430 reasons this only happens if the program is not SUID or SGID enabled.
3432 @item
3433 The @var{dir} argument, if it is not a null pointer.
3435 @item
3436 The value of the @code{P_tmpdir} macro.
3438 @item
3439 The directory @file{/tmp}.
3440 @end itemize
3442 This function is defined for SVID compatibility.
3444 @strong{Warning:} Between the time the pathname is constructed and the
3445 file is created another process might have created a file with the same
3446 name using @code{tempnam}, leading to a possible security hole.  The
3447 implementation generates names which can hardly be predicted, but when
3448 opening the file you should use the @code{O_EXCL} flag.  Using
3449 @code{tmpfile} or @code{mkstemp} is a safe way to avoid this problem.
3450 @end deftypefun
3451 @cindex TMPDIR environment variable
3453 @c !!! are we putting SVID/GNU/POSIX.1/BSD in here or not??
3454 @deftypevr {SVID Macro} {char *} P_tmpdir
3455 @standards{SVID, stdio.h}
3456 This macro is the name of the default directory for temporary files.
3457 @end deftypevr
3459 Older Unix systems did not have the functions just described.  Instead
3460 they used @code{mktemp} and @code{mkstemp}.  Both of these functions
3461 work by modifying a file name template string you pass.  The last six
3462 characters of this string must be @samp{XXXXXX}.  These six @samp{X}s
3463 are replaced with six characters which make the whole string a unique
3464 file name.  Usually the template string is something like
3465 @samp{/tmp/@var{prefix}XXXXXX}, and each program uses a unique @var{prefix}.
3467 @strong{NB:} Because @code{mktemp} and @code{mkstemp} modify the
3468 template string, you @emph{must not} pass string constants to them.
3469 String constants are normally in read-only storage, so your program
3470 would crash when @code{mktemp} or @code{mkstemp} tried to modify the
3471 string.  These functions are declared in the header file @file{stdlib.h}.
3472 @pindex stdlib.h
3474 @deftypefun {char *} mktemp (char *@var{template})
3475 @standards{Unix, stdlib.h}
3476 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3477 @c __gen_tempname (caller tmpl, __GT_NOCREATE) ok
3478 The @code{mktemp} function generates a unique file name by modifying
3479 @var{template} as described above.  If successful, it returns
3480 @var{template} as modified.  If @code{mktemp} cannot find a unique file
3481 name, it makes @var{template} an empty string and returns that.  If
3482 @var{template} does not end with @samp{XXXXXX}, @code{mktemp} returns a
3483 null pointer.
3485 @strong{Warning:} Between the time the pathname is constructed and the
3486 file is created another process might have created a file with the same
3487 name using @code{mktemp}, leading to a possible security hole.  The
3488 implementation generates names which can hardly be predicted, but when
3489 opening the file you should use the @code{O_EXCL} flag.  Using
3490 @code{mkstemp} is a safe way to avoid this problem.
3491 @end deftypefun
3493 @deftypefun int mkstemp (char *@var{template})
3494 @standards{BSD, stdlib.h}
3495 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
3496 @c __gen_tempname (caller tmpl, __GT_FILE) ok
3497 The @code{mkstemp} function generates a unique file name just as
3498 @code{mktemp} does, but it also opens the file for you with @code{open}
3499 (@pxref{Opening and Closing Files}).  If successful, it modifies
3500 @var{template} in place and returns a file descriptor for that file open
3501 for reading and writing.  If @code{mkstemp} cannot create a
3502 uniquely-named file, it returns @code{-1}.  If @var{template} does not
3503 end with @samp{XXXXXX}, @code{mkstemp} returns @code{-1} and does not
3504 modify @var{template}.
3506 The file is opened using mode @code{0600}.  If the file is meant to be
3507 used by other users this mode must be changed explicitly.
3508 @end deftypefun
3510 Unlike @code{mktemp}, @code{mkstemp} is actually guaranteed to create a
3511 unique file that cannot possibly clash with any other program trying to
3512 create a temporary file.  This is because it works by calling
3513 @code{open} with the @code{O_EXCL} flag, which says you want to create a
3514 new file and get an error if the file already exists.
3516 @deftypefun {char *} mkdtemp (char *@var{template})
3517 @standards{BSD, stdlib.h}
3518 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3519 @c __gen_tempname (caller tmpl, __GT_DIR) ok
3520 The @code{mkdtemp} function creates a directory with a unique name.  If
3521 it succeeds, it overwrites @var{template} with the name of the
3522 directory, and returns @var{template}.  As with @code{mktemp} and
3523 @code{mkstemp}, @var{template} should be a string ending with
3524 @samp{XXXXXX}.
3526 If @code{mkdtemp} cannot create an uniquely named directory, it returns
3527 @code{NULL} and sets @var{errno} appropriately.  If @var{template} does
3528 not end with @samp{XXXXXX}, @code{mkdtemp} returns @code{NULL} and does
3529 not modify @var{template}.  @var{errno} will be set to @code{EINVAL} in
3530 this case.
3532 The directory is created using mode @code{0700}.
3533 @end deftypefun
3535 The directory created by @code{mkdtemp} cannot clash with temporary
3536 files or directories created by other users.  This is because directory
3537 creation always works like @code{open} with @code{O_EXCL}.
3538 @xref{Creating Directories}.
3540 The @code{mkdtemp} function comes from OpenBSD.
3542 @c FIXME these are undocumented:
3543 @c faccessat
3544 @c fchmodat
3545 @c fchownat
3546 @c futimesat
3547 @c fstatat (there's a commented-out safety assessment for this one)
3548 @c statx
3549 @c mkdirat
3550 @c mkfifoat
3551 @c name_to_handle_at
3552 @c openat
3553 @c open_by_handle_at
3554 @c readlinkat
3555 @c renameat
3556 @c renameat2
3557 @c scandirat
3558 @c symlinkat
3559 @c unlinkat
3560 @c utimensat
3561 @c mknodat