(CFLAGS-tst-align.c): Add -mpreferred-stack-boundary=4.
[glibc.git] / manual / filesys.texi
blob70889c2f85b14c2cebd7d47139022e40e1596b9c
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 the GNU C library's functions for manipulating
6 files.  Unlike the input and output functions (@pxref{I/O on Streams};
7 @pxref{Low-Level I/O}), these functions are concerned with operating
8 on the files themselves rather than on their contents.
10 Among the facilities described in this chapter are functions for
11 examining or modifying directories, functions for renaming and deleting
12 files, and functions for examining and setting file attributes such as
13 access permissions and modification times.
15 @menu
16 * Working Directory::           This is used to resolve relative
17                                  file names.
18 * Accessing Directories::       Finding out what files a directory
19                                  contains.
20 * Working with Directory Trees:: Apply actions to all files or a selectable
21                                  subset of a directory hierarchy.
22 * Hard Links::                  Adding alternate names to a file.
23 * Symbolic Links::              A file that ``points to'' a file name.
24 * Deleting Files::              How to delete a file, and what that means.
25 * Renaming Files::              Changing a file's name.
26 * Creating Directories::        A system call just for creating a directory.
27 * File Attributes::             Attributes of individual files.
28 * Making Special Files::        How to create special files.
29 * Temporary Files::             Naming and creating temporary files.
30 @end menu
32 @node Working Directory
33 @section Working Directory
35 @cindex current working directory
36 @cindex working directory
37 @cindex change working directory
38 Each process has associated with it a directory, called its @dfn{current
39 working directory} or simply @dfn{working directory}, that is used in
40 the resolution of relative file names (@pxref{File Name Resolution}).
42 When you log in and begin a new session, your working directory is
43 initially set to the home directory associated with your login account
44 in the system user database.  You can find any user's home directory
45 using the @code{getpwuid} or @code{getpwnam} functions; see @ref{User
46 Database}.
48 Users can change the working directory using shell commands like
49 @code{cd}.  The functions described in this section are the primitives
50 used by those commands and by other programs for examining and changing
51 the working directory.
52 @pindex cd
54 Prototypes for these functions are declared in the header file
55 @file{unistd.h}.
56 @pindex unistd.h
58 @comment unistd.h
59 @comment POSIX.1
60 @deftypefun {char *} getcwd (char *@var{buffer}, size_t @var{size})
61 The @code{getcwd} function returns an absolute file name representing
62 the current working directory, storing it in the character array
63 @var{buffer} that you provide.  The @var{size} argument is how you tell
64 the system the allocation size of @var{buffer}.
66 The GNU library version of this function also permits you to specify a
67 null pointer for the @var{buffer} argument.  Then @code{getcwd}
68 allocates a buffer automatically, as with @code{malloc}
69 (@pxref{Unconstrained Allocation}).  If the @var{size} is greater than
70 zero, then the buffer is that large; otherwise, the buffer is as large
71 as necessary to hold the result.
73 The return value is @var{buffer} on success and a null pointer on failure.
74 The following @code{errno} error conditions are defined for this function:
76 @table @code
77 @item EINVAL
78 The @var{size} argument is zero and @var{buffer} is not a null pointer.
80 @item ERANGE
81 The @var{size} argument is less than the length of the working directory
82 name.  You need to allocate a bigger array and try again.
84 @item EACCES
85 Permission to read or search a component of the file name was denied.
86 @end table
87 @end deftypefun
89 You could implement the behavior of GNU's @w{@code{getcwd (NULL, 0)}}
90 using only the standard behavior of @code{getcwd}:
92 @smallexample
93 char *
94 gnu_getcwd ()
96   size_t size = 100;
98   while (1)
99     @{
100       char *buffer = (char *) xmalloc (size);
101       if (getcwd (buffer, size) == buffer)
102         return buffer;
103       free (buffer);
104       if (errno != ERANGE)
105         return 0;
106       size *= 2;
107     @}
109 @end smallexample
111 @noindent
112 @xref{Malloc Examples}, for information about @code{xmalloc}, which is
113 not a library function but is a customary name used in most GNU
114 software.
116 @comment unistd.h
117 @comment BSD
118 @deftypefn {Deprecated Function} {char *} getwd (char *@var{buffer})
119 This is similar to @code{getcwd}, but has no way to specify the size of
120 the buffer.  The GNU library provides @code{getwd} only
121 for backwards compatibility with BSD.
123 The @var{buffer} argument should be a pointer to an array at least
124 @code{PATH_MAX} bytes long (@pxref{Limits for Files}).  In the GNU
125 system there is no limit to the size of a file name, so this is not
126 necessarily enough space to contain the directory name.  That is why
127 this function is deprecated.
128 @end deftypefn
130 @comment unistd.h
131 @comment GNU
132 @deftypefun {char *} get_current_dir_name (void)
133 @vindex PWD
134 This @code{get_current_dir_name} function is bascially equivalent to
135 @w{@code{getcwd (NULL, 0)}}.  The only difference is that the value of
136 the @code{PWD} variable is returned if this value is correct.  This is a
137 subtle difference which is visible if the path described by the
138 @code{PWD} value is using one or more symbol links in which case the
139 value returned by @code{getcwd} can resolve the symbol links and
140 therefore yield a different result.
142 This function is a GNU extension.
143 @end deftypefun
145 @comment unistd.h
146 @comment POSIX.1
147 @deftypefun int chdir (const char *@var{filename})
148 This function is used to set the process's working directory to
149 @var{filename}.
151 The normal, successful return value from @code{chdir} is @code{0}.  A
152 value of @code{-1} is returned to indicate an error.  The @code{errno}
153 error conditions defined for this function are the usual file name
154 syntax errors (@pxref{File Name Errors}), plus @code{ENOTDIR} if the
155 file @var{filename} is not a directory.
156 @end deftypefun
158 @comment unistd.h
159 @comment XPG
160 @deftypefun int fchdir (int @var{filedes})
161 This function is used to set the process's working directory to
162 directory associated with the file descriptor @var{filedes}.
164 The normal, successful return value from @code{fchdir} is @code{0}.  A
165 value of @code{-1} is returned to indicate an error.  The following
166 @code{errno} error conditions are defined for this function:
168 @table @code
169 @item EACCES
170 Read permission is denied for the directory named by @code{dirname}.
172 @item EBADF
173 The @var{filedes} argument is not a valid file descriptor.
175 @item ENOTDIR
176 The file descriptor @var{filedes} is not associated with a directory.
178 @item EINTR
179 The function call was interrupt by a signal.
181 @item EIO
182 An I/O error occurred.
183 @end table
184 @end deftypefun
187 @node Accessing Directories
188 @section Accessing Directories
189 @cindex accessing directories
190 @cindex reading from a directory
191 @cindex directories, accessing
193 The facilities described in this section let you read the contents of a
194 directory file.  This is useful if you want your program to list all the
195 files in a directory, perhaps as part of a menu.
197 @cindex directory stream
198 The @code{opendir} function opens a @dfn{directory stream} whose
199 elements are directory entries.  You use the @code{readdir} function on
200 the directory stream to retrieve these entries, represented as
201 @w{@code{struct dirent}} objects.  The name of the file for each entry is
202 stored in the @code{d_name} member of this structure.  There are obvious
203 parallels here to the stream facilities for ordinary files, described in
204 @ref{I/O on Streams}.
206 @menu
207 * Directory Entries::           Format of one directory entry.
208 * Opening a Directory::         How to open a directory stream.
209 * Reading/Closing Directory::   How to read directory entries from the stream.
210 * Simple Directory Lister::     A very simple directory listing program.
211 * Random Access Directory::     Rereading part of the directory
212                                  already read with the same stream.
213 * Scanning Directory Content::  Get entries for user selected subset of
214                                  contents in given directory.
215 * Simple Directory Lister Mark II::  Revised version of the program.
216 @end menu
218 @node Directory Entries
219 @subsection Format of a Directory Entry
221 @pindex dirent.h
222 This section describes what you find in a single directory entry, as you
223 might obtain it from a directory stream.  All the symbols are declared
224 in the header file @file{dirent.h}.
226 @comment dirent.h
227 @comment POSIX.1
228 @deftp {Data Type} {struct dirent}
229 This is a structure type used to return information about directory
230 entries.  It contains the following fields:
232 @table @code
233 @item char d_name[]
234 This is the null-terminated file name component.  This is the only
235 field you can count on in all POSIX systems.
237 @item ino_t d_fileno
238 This is the file serial number.  For BSD compatibility, you can also
239 refer to this member as @code{d_ino}.  In the GNU system and most POSIX
240 systems, for most files this the same as the @code{st_ino} member that
241 @code{stat} will return for the file.  @xref{File Attributes}.
243 @item unsigned char d_namlen
244 This is the length of the file name, not including the terminating null
245 character.  Its type is @code{unsigned char} because that is the integer
246 type of the appropriate size
248 @item unsigned char d_type
249 This is the type of the file, possibly unknown.  The following constants
250 are defined for its value:
252 @vtable @code
253 @item DT_UNKNOWN
254 The type is unknown.  On some systems this is the only value returned.
256 @item DT_REG
257 A regular file.
259 @item DT_DIR
260 A directory.
262 @item DT_FIFO
263 A named pipe, or FIFO.  @xref{FIFO Special Files}.
265 @item DT_SOCK
266 A local-domain socket.  @c !!! @xref{Local Domain}.
268 @item DT_CHR
269 A character device.
271 @item DT_BLK
272 A block device.
273 @end vtable
275 This member is a BSD extension.  The symbol @code{_DIRENT_HAVE_D_TYPE}
276 is defined if this member is available.  On systems where it is used, it
277 corresponds to the file type bits in the @code{st_mode} member of
278 @code{struct statbuf}.  If the value cannot be determine the member
279 value is DT_UNKNOWN.  These two macros convert between @code{d_type}
280 values and @code{st_mode} values:
282 @comment dirent.h
283 @comment BSD
284 @deftypefun int IFTODT (mode_t @var{mode})
285 This returns the @code{d_type} value corresponding to @var{mode}.
286 @end deftypefun
288 @comment dirent.h
289 @comment BSD
290 @deftypefun mode_t DTTOIF (int @var{dtype})
291 This returns the @code{st_mode} value corresponding to @var{dtype}.
292 @end deftypefun
293 @end table
295 This structure may contain additional members in the future.  Their
296 availability is always announced in the compilation environment by a
297 macro names @code{_DIRENT_HAVE_D_@var{xxx}} where @var{xxx} is replaced
298 by the name of the new member.  For instance, the member @code{d_reclen}
299 available on some systems is announced through the macro
300 @code{_DIRENT_HAVE_D_RECLEN}.
302 When a file has multiple names, each name has its own directory entry.
303 The only way you can tell that the directory entries belong to a
304 single file is that they have the same value for the @code{d_fileno}
305 field.
307 File attributes such as size, modification times etc., are part of the
308 file itself, not of any particular directory entry.  @xref{File
309 Attributes}.
310 @end deftp
312 @node Opening a Directory
313 @subsection Opening a Directory Stream
315 @pindex dirent.h
316 This section describes how to open a directory stream.  All the symbols
317 are declared in the header file @file{dirent.h}.
319 @comment dirent.h
320 @comment POSIX.1
321 @deftp {Data Type} DIR
322 The @code{DIR} data type represents a directory stream.
323 @end deftp
325 You shouldn't ever allocate objects of the @code{struct dirent} or
326 @code{DIR} data types, since the directory access functions do that for
327 you.  Instead, you refer to these objects using the pointers returned by
328 the following functions.
330 @comment dirent.h
331 @comment POSIX.1
332 @deftypefun {DIR *} opendir (const char *@var{dirname})
333 The @code{opendir} function opens and returns a directory stream for
334 reading the directory whose file name is @var{dirname}.  The stream has
335 type @code{DIR *}.
337 If unsuccessful, @code{opendir} returns a null pointer.  In addition to
338 the usual file name errors (@pxref{File Name Errors}), the
339 following @code{errno} error conditions are defined for this function:
341 @table @code
342 @item EACCES
343 Read permission is denied for the directory named by @code{dirname}.
345 @item EMFILE
346 The process has too many files open.
348 @item ENFILE
349 The entire system, or perhaps the file system which contains the
350 directory, cannot support any additional open files at the moment.
351 (This problem cannot happen on the GNU system.)
352 @end table
354 The @code{DIR} type is typically implemented using a file descriptor,
355 and the @code{opendir} function in terms of the @code{open} function.
356 @xref{Low-Level I/O}.  Directory streams and the underlying
357 file descriptors are closed on @code{exec} (@pxref{Executing a File}).
358 @end deftypefun
360 In some situations it can be desirable to get hold of the file
361 descriptor which is created by the @code{opendir} call.  For instance,
362 to switch the current working directory to the directory just read the
363 @code{fchdir} function could be used.  Historically the @code{DIR} type
364 was exposed and programs could access the fields.  This does not happen
365 in the GNU C library.  Instead a separate function is provided to allow
366 access.
368 @comment dirent.h
369 @comment GNU
370 @deftypefun int dirfd (DIR *@var{dirstream})
371 The function @code{dirfd} returns the file descriptor associated with
372 the directory stream @var{dirstream}.  This descriptor can be used until
373 the directory is closed with @code{closedir}.  If the directory stream
374 implementation is not using file descriptors the return value is
375 @code{-1}.
376 @end deftypefun
378 @node Reading/Closing Directory
379 @subsection Reading and Closing a Directory Stream
381 @pindex dirent.h
382 This section describes how to read directory entries from a directory
383 stream, and how to close the stream when you are done with it.  All the
384 symbols are declared in the header file @file{dirent.h}.
386 @comment dirent.h
387 @comment POSIX.1
388 @deftypefun {struct dirent *} readdir (DIR *@var{dirstream})
389 This function reads the next entry from the directory.  It normally
390 returns a pointer to a structure containing information about the file.
391 This structure is statically allocated and can be rewritten by a
392 subsequent call.
394 @strong{Portability Note:} On some systems @code{readdir} may not
395 return entries for @file{.} and @file{..}, even though these are always
396 valid file names in any directory.  @xref{File Name Resolution}.
398 If there are no more entries in the directory or an error is detected,
399 @code{readdir} returns a null pointer.  The following @code{errno} error
400 conditions are defined for this function:
402 @table @code
403 @item EBADF
404 The @var{dirstream} argument is not valid.
405 @end table
407 @code{readdir} is not thread safe.  Multiple threads using
408 @code{readdir} on the same @var{dirstream} may overwrite the return
409 value.  Use @code{readdir_r} when this is critical.
410 @end deftypefun
412 @comment dirent.h
413 @comment GNU
414 @deftypefun int readdir_r (DIR *@var{dirstream}, struct dirent *@var{entry}, struct dirent **@var{result})
415 This function is the reentrant version of @code{readdir}.  Like
416 @code{readdir} it returns the next entry from the directory.  But to
417 prevent conflicts between simultaneously running threads the result is
418 not stored in statically allocated memory.  Instead the argument
419 @var{entry} points to a place to store the result.
421 Normally @code{readdir_r} returns zero and sets @code{*@var{result}}
422 to @var{entry}.  If there are no more entries in the directory or an
423 error is detected, @code{readdir_r} sets @code{*@var{result}} to a
424 null pointer and returns a nonzero error code, also stored in
425 @code{errno}, as described for @code{readdir}.
427 @strong{Portability Note:} On some systems @code{readdir_r} may not
428 return a NUL terminated string for the file name, even when there is no
429 @code{d_reclen} field in @code{struct dirent} and the file
430 name is the maximum allowed size.  Modern systems all have the
431 @code{d_reclen} field, and on old systems multi-threading is not
432 critical.  In any case there is no such problem with the @code{readdir}
433 function, so that even on systems without the @code{d_reclen} member one
434 could use multiple threads by using external locking.
436 It is also important to look at the definition of the @code{struct
437 dirent} type.  Simply passing a pointer to an object of this type for
438 the second parameter of @code{readdir_r} might not be enough.  Some
439 systems don't define the @code{d_name} element sufficiently long.  In
440 this case the user has to provide additional space.  There must be room
441 for at least @code{NAME_MAX + 1} characters in the @code{d_name} array.
442 Code to call @code{readdir_r} could look like this:
444 @smallexample
445   union
446   @{
447     struct dirent d;
448     char b[offsetof (struct dirent, d_name) + NAME_MAX + 1];
449   @} u;
451   if (readdir_r (dir, &u.d, &res) == 0)
452     @dots{}
453 @end smallexample
454 @end deftypefun
456 To support large filesystems on 32-bit machines there are LFS variants
457 of the last two functions.
459 @comment dirent.h
460 @comment LFS
461 @deftypefun {struct dirent64 *} readdir64 (DIR *@var{dirstream})
462 The @code{readdir64} function is just like the @code{readdir} function
463 except that it returns a pointer to a record of type @code{struct
464 dirent64}.  Some of the members of this data type (notably @code{d_ino})
465 might have a different size to allow large filesystems.
467 In all other aspects this function is equivalent to @code{readdir}.
468 @end deftypefun
470 @comment dirent.h
471 @comment LFS
472 @deftypefun int readdir64_r (DIR *@var{dirstream}, struct dirent64 *@var{entry}, struct dirent64 **@var{result})
473 The @code{readdir64_r} function is equivalent to the @code{readdir_r}
474 function except that it takes parameters of base type @code{struct
475 dirent64} instead of @code{struct dirent} in the second and third
476 position.  The same precautions mentioned in the documentation of
477 @code{readdir_r} also apply here.
478 @end deftypefun
480 @comment dirent.h
481 @comment POSIX.1
482 @deftypefun int closedir (DIR *@var{dirstream})
483 This function closes the directory stream @var{dirstream}.  It returns
484 @code{0} on success and @code{-1} on failure.
486 The following @code{errno} error conditions are defined for this
487 function:
489 @table @code
490 @item EBADF
491 The @var{dirstream} argument is not valid.
492 @end table
493 @end deftypefun
495 @node Simple Directory Lister
496 @subsection Simple Program to List a Directory
498 Here's a simple program that prints the names of the files in
499 the current working directory:
501 @smallexample
502 @include dir.c.texi
503 @end smallexample
505 The order in which files appear in a directory tends to be fairly
506 random.  A more useful program would sort the entries (perhaps by
507 alphabetizing them) before printing them; see
508 @ref{Scanning Directory Content}, and @ref{Array Sort Function}.
511 @node Random Access Directory
512 @subsection Random Access in a Directory Stream
514 @pindex dirent.h
515 This section describes how to reread parts of a directory that you have
516 already read from an open directory stream.  All the symbols are
517 declared in the header file @file{dirent.h}.
519 @comment dirent.h
520 @comment POSIX.1
521 @deftypefun void rewinddir (DIR *@var{dirstream})
522 The @code{rewinddir} function is used to reinitialize the directory
523 stream @var{dirstream}, so that if you call @code{readdir} it
524 returns information about the first entry in the directory again.  This
525 function also notices if files have been added or removed to the
526 directory since it was opened with @code{opendir}.  (Entries for these
527 files might or might not be returned by @code{readdir} if they were
528 added or removed since you last called @code{opendir} or
529 @code{rewinddir}.)
530 @end deftypefun
532 @comment dirent.h
533 @comment BSD
534 @deftypefun off_t telldir (DIR *@var{dirstream})
535 The @code{telldir} function returns the file position of the directory
536 stream @var{dirstream}.  You can use this value with @code{seekdir} to
537 restore the directory stream to that position.
538 @end deftypefun
540 @comment dirent.h
541 @comment BSD
542 @deftypefun void seekdir (DIR *@var{dirstream}, off_t @var{pos})
543 The @code{seekdir} function sets the file position of the directory
544 stream @var{dirstream} to @var{pos}.  The value @var{pos} must be the
545 result of a previous call to @code{telldir} on this particular stream;
546 closing and reopening the directory can invalidate values returned by
547 @code{telldir}.
548 @end deftypefun
551 @node Scanning Directory Content
552 @subsection Scanning the Content of a Directory
554 A higher-level interface to the directory handling functions is the
555 @code{scandir} function.  With its help one can select a subset of the
556 entries in a directory, possibly sort them and get a list of names as
557 the result.
559 @comment dirent.h
560 @comment BSD/SVID
561 @deftypefun int scandir (const char *@var{dir}, struct dirent ***@var{namelist}, int (*@var{selector}) (const struct dirent *), int (*@var{cmp}) (const void *, const void *))
563 The @code{scandir} function scans the contents of the directory selected
564 by @var{dir}.  The result in *@var{namelist} is an array of pointers to
565 structure of type @code{struct dirent} which describe all selected
566 directory entries and which is allocated using @code{malloc}.  Instead
567 of always getting all directory entries returned, the user supplied
568 function @var{selector} can be used to decide which entries are in the
569 result.  Only the entries for which @var{selector} returns a non-zero
570 value are selected.
572 Finally the entries in *@var{namelist} are sorted using the
573 user-supplied function @var{cmp}.  The arguments passed to the @var{cmp}
574 function are of type @code{struct dirent **}, therefore one cannot
575 directly use the @code{strcmp} or @code{strcoll} functions; instead see
576 the functions @code{alphasort} and @code{versionsort} below.
578 The return value of the function is the number of entries placed in
579 *@var{namelist}.  If it is @code{-1} an error occurred (either the
580 directory could not be opened for reading or the malloc call failed) and
581 the global variable @code{errno} contains more information on the error.
582 @end deftypefun
584 As described above the fourth argument to the @code{scandir} function
585 must be a pointer to a sorting function.  For the convenience of the
586 programmer the GNU C library contains implementations of functions which
587 are very helpful for this purpose.
589 @comment dirent.h
590 @comment BSD/SVID
591 @deftypefun int alphasort (const void *@var{a}, const void *@var{b})
592 The @code{alphasort} function behaves like the @code{strcoll} function
593 (@pxref{String/Array Comparison}).  The difference is that the arguments
594 are not string pointers but instead they are of type
595 @code{struct dirent **}.
597 The return value of @code{alphasort} is less than, equal to, or greater
598 than zero depending on the order of the two entries @var{a} and @var{b}.
599 @end deftypefun
601 @comment dirent.h
602 @comment GNU
603 @deftypefun int versionsort (const void *@var{a}, const void *@var{b})
604 The @code{versionsort} function is like @code{alphasort} except that it
605 uses the @code{strverscmp} function internally.
606 @end deftypefun
608 If the filesystem supports large files we cannot use the @code{scandir}
609 anymore since the @code{dirent} structure might not able to contain all
610 the information.  The LFS provides the new type @w{@code{struct
611 dirent64}}.  To use this we need a new function.
613 @comment dirent.h
614 @comment GNU
615 @deftypefun int scandir64 (const char *@var{dir}, struct dirent64 ***@var{namelist}, int (*@var{selector}) (const struct dirent64 *), int (*@var{cmp}) (const void *, const void *))
616 The @code{scandir64} function works like the @code{scandir} function
617 except that the directory entries it returns are described by elements
618 of type @w{@code{struct dirent64}}.  The function pointed to by
619 @var{selector} is again used to select the desired entries, except that
620 @var{selector} now must point to a function which takes a
621 @w{@code{struct dirent64 *}} parameter.
623 Similarly the @var{cmp} function should expect its two arguments to be
624 of type @code{struct dirent64 **}.
625 @end deftypefun
627 As @var{cmp} is now a function of a different type, the functions
628 @code{alphasort} and @code{versionsort} cannot be supplied for that
629 argument.  Instead we provide the two replacement functions below.
631 @comment dirent.h
632 @comment GNU
633 @deftypefun int alphasort64 (const void *@var{a}, const void *@var{b})
634 The @code{alphasort64} function behaves like the @code{strcoll} function
635 (@pxref{String/Array Comparison}).  The difference is that the arguments
636 are not string pointers but instead they are of type
637 @code{struct dirent64 **}.
639 Return value of @code{alphasort64} is less than, equal to, or greater
640 than zero depending on the order of the two entries @var{a} and @var{b}.
641 @end deftypefun
643 @comment dirent.h
644 @comment GNU
645 @deftypefun int versionsort64 (const void *@var{a}, const void *@var{b})
646 The @code{versionsort64} function is like @code{alphasort64}, excepted that it
647 uses the @code{strverscmp} function internally.
648 @end deftypefun
650 It is important not to mix the use of @code{scandir} and the 64-bit
651 comparison functions or vice versa.  There are systems on which this
652 works but on others it will fail miserably.
654 @node Simple Directory Lister Mark II
655 @subsection Simple Program to List a Directory, Mark II
657 Here is a revised version of the directory lister found above
658 (@pxref{Simple Directory Lister}).  Using the @code{scandir} function we
659 can avoid the functions which work directly with the directory contents.
660 After the call the returned entries are available for direct use.
662 @smallexample
663 @include dir2.c.texi
664 @end smallexample
666 Note the simple selector function in this example.  Since we want to see
667 all directory entries we always return @code{1}.
670 @node Working with Directory Trees
671 @section Working with Directory Trees
672 @cindex directory hierarchy
673 @cindex hierarchy, directory
674 @cindex tree, directory
676 The functions described so far for handling the files in a directory
677 have allowed you to either retrieve the information bit by bit, or to
678 process all the files as a group (see @code{scandir}).  Sometimes it is
679 useful to process whole hierarchies of directories and their contained
680 files.  The X/Open specification defines two functions to do this.  The
681 simpler form is derived from an early definition in @w{System V} systems
682 and therefore this function is available on SVID-derived systems.  The
683 prototypes and required definitions can be found in the @file{ftw.h}
684 header.
686 There are four functions in this family: @code{ftw}, @code{nftw} and
687 their 64-bit counterparts @code{ftw64} and @code{nftw64}.  These
688 functions take as one of their arguments a pointer to a callback
689 function of the appropriate type.
691 @comment ftw.h
692 @comment GNU
693 @deftp {Data Type} __ftw_func_t
695 @smallexample
696 int (*) (const char *, const struct stat *, int)
697 @end smallexample
699 The type of callback functions given to the @code{ftw} function.  The
700 first parameter points to the file name, the second parameter to an
701 object of type @code{struct stat} which is filled in for the file named
702 in the first parameter.
704 @noindent
705 The last parameter is a flag giving more information about the current
706 file.  It can have the following values:
708 @vtable @code
709 @item FTW_F
710 The item is either a normal file or a file which does not fit into one
711 of the following categories.  This could be special files, sockets etc.
712 @item FTW_D
713 The item is a directory.
714 @item FTW_NS
715 The @code{stat} call failed and so the information pointed to by the
716 second paramater is invalid.
717 @item FTW_DNR
718 The item is a directory which cannot be read.
719 @item FTW_SL
720 The item is a symbolic link.  Since symbolic links are normally followed
721 seeing this value in a @code{ftw} callback function means the referenced
722 file does not exist.  The situation for @code{nftw} is different.
724 This value is only available if the program is compiled with
725 @code{_BSD_SOURCE} or @code{_XOPEN_EXTENDED} defined before including
726 the first header.  The original SVID systems do not have symbolic links.
727 @end vtable
729 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
730 type is in fact @code{__ftw64_func_t} since this mode changes
731 @code{struct stat} to be @code{struct stat64}.
732 @end deftp
734 For the LFS interface and for use in the function @code{ftw64}, the
735 header @file{ftw.h} defines another function type.
737 @comment ftw.h
738 @comment GNU
739 @deftp {Data Type} __ftw64_func_t
741 @smallexample
742 int (*) (const char *, const struct stat64 *, int)
743 @end smallexample
745 This type is used just like @code{__ftw_func_t} for the callback
746 function, but this time is called from @code{ftw64}.  The second
747 parameter to the function is a pointer to a variable of type
748 @code{struct stat64} which is able to represent the larger values.
749 @end deftp
751 @comment ftw.h
752 @comment GNU
753 @deftp {Data Type} __nftw_func_t
755 @smallexample
756 int (*) (const char *, const struct stat *, int, struct FTW *)
757 @end smallexample
759 @vindex FTW_DP
760 @vindex FTW_SLN
761 The first three arguments are the same as for the @code{__ftw_func_t}
762 type.  However for the third argument some additional values are defined
763 to allow finer differentiation:
764 @table @code
765 @item FTW_DP
766 The current item is a directory and all subdirectories have already been
767 visited and reported.  This flag is returned instead of @code{FTW_D} if
768 the @code{FTW_DEPTH} flag is passed to @code{nftw} (see below).
769 @item FTW_SLN
770 The current item is a stale symbolic link.  The file it points to does
771 not exist.
772 @end table
774 The last parameter of the callback function is a pointer to a structure
775 with some extra information as described below.
777 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
778 type is in fact @code{__nftw64_func_t} since this mode changes
779 @code{struct stat} to be @code{struct stat64}.
780 @end deftp
782 For the LFS interface there is also a variant of this data type
783 available which has to be used with the @code{nftw64} function.
785 @comment ftw.h
786 @comment GNU
787 @deftp {Data Type} __nftw64_func_t
789 @smallexample
790 int (*) (const char *, const struct stat64 *, int, struct FTW *)
791 @end smallexample
793 This type is used just like @code{__nftw_func_t} for the callback
794 function, but this time is called from @code{nftw64}.  The second
795 parameter to the function is this time a pointer to a variable of type
796 @code{struct stat64} which is able to represent the larger values.
797 @end deftp
799 @comment ftw.h
800 @comment XPG4.2
801 @deftp {Data Type} {struct FTW}
802 The information contained in this structure helps in interpreting the
803 name parameter and gives some information about the current state of the
804 traversal of the directory hierarchy.
806 @table @code
807 @item int base
808 The value is the offset into the string passed in the first parameter to
809 the callback function of the beginning of the file name.  The rest of
810 the string is the path of the file.  This information is especially
811 important if the @code{FTW_CHDIR} flag was set in calling @code{nftw}
812 since then the current directory is the one the current item is found
814 @item int level
815 Whilst processing, the code tracks how many directories down it has gone
816 to find the current file.  This nesting level starts at @math{0} for
817 files in the initial directory (or is zero for the initial file if a
818 file was passed).
819 @end table
820 @end deftp
823 @comment ftw.h
824 @comment SVID
825 @deftypefun int ftw (const char *@var{filename}, __ftw_func_t @var{func}, int @var{descriptors})
826 The @code{ftw} function calls the callback function given in the
827 parameter @var{func} for every item which is found in the directory
828 specified by @var{filename} and all directories below.  The function
829 follows symbolic links if necessary but does not process an item twice.
830 If @var{filename} is not a directory then it itself is the only object
831 returned to the callback function.
833 The file name passed to the callback function is constructed by taking
834 the @var{filename} parameter and appending the names of all passed
835 directories and then the local file name.  So the callback function can
836 use this parameter to access the file.  @code{ftw} also calls
837 @code{stat} for the file and passes that information on to the callback
838 function.  If this @code{stat} call was not successful the failure is
839 indicated by setting the third argument of the callback function to
840 @code{FTW_NS}.  Otherwise it is set according to the description given
841 in the account of @code{__ftw_func_t} above.
843 The callback function is expected to return @math{0} to indicate that no
844 error occurred and that processing should continue.  If an error
845 occurred in the callback function or it wants @code{ftw} to return
846 immediately, the callback function can return a value other than
847 @math{0}.  This is the only correct way to stop the function.  The
848 program must not use @code{setjmp} or similar techniques to continue
849 from another place.  This would leave resources allocated by the
850 @code{ftw} function unfreed.
852 The @var{descriptors} parameter to @code{ftw} specifies how many file
853 descriptors it is allowed to consume.  The function runs faster the more
854 descriptors it can use.  For each level in the directory hierarchy at
855 most one descriptor is used, but for very deep ones any limit on open
856 file descriptors for the process or the system may be exceeded.
857 Moreover, file descriptor limits in a multi-threaded program apply to
858 all the threads as a group, and therefore it is a good idea to supply a
859 reasonable limit to the number of open descriptors.
861 The return value of the @code{ftw} function is @math{0} if all callback
862 function calls returned @math{0} and all actions performed by the
863 @code{ftw} succeeded.  If a function call failed (other than calling
864 @code{stat} on an item) the function returns @math{-1}.  If a callback
865 function returns a value other than @math{0} this value is returned as
866 the return value of @code{ftw}.
868 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
869 32-bit system this function is in fact @code{ftw64}, i.e. the LFS
870 interface transparently replaces the old interface.
871 @end deftypefun
873 @comment ftw.h
874 @comment Unix98
875 @deftypefun int ftw64 (const char *@var{filename}, __ftw64_func_t @var{func}, int @var{descriptors})
876 This function is similar to @code{ftw} but it can work on filesystems
877 with large files.  File information is reported using a variable of type
878 @code{struct stat64} which is passed by reference to the callback
879 function.
881 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
882 32-bit system this function is available under the name @code{ftw} and
883 transparently replaces the old implementation.
884 @end deftypefun
886 @comment ftw.h
887 @comment XPG4.2
888 @deftypefun int nftw (const char *@var{filename}, __nftw_func_t @var{func}, int @var{descriptors}, int @var{flag})
889 The @code{nftw} function works like the @code{ftw} functions.  They call
890 the callback function @var{func} for all items found in the directory
891 @var{filename} and below.  At most @var{descriptors} file descriptors
892 are consumed during the @code{nftw} call.
894 One difference is that the callback function is of a different type.  It
895 is of type @w{@code{struct FTW *}} and provides the callback function
896 with the extra information described above.
898 A second difference is that @code{nftw} takes a fourth argument, which
899 is @math{0} or a bitwise-OR combination of any of the following values.
901 @vtable @code
902 @item FTW_PHYS
903 While traversing the directory symbolic links are not followed.  Instead
904 symbolic links are reported using the @code{FTW_SL} value for the type
905 parameter to the callback function.  If the file referenced by a
906 symbolic link does not exist @code{FTW_SLN} is returned instead.
907 @item FTW_MOUNT
908 The callback function is only called for items which are on the same
909 mounted filesystem as the directory given by the @var{filename}
910 parameter to @code{nftw}.
911 @item FTW_CHDIR
912 If this flag is given the current working directory is changed to the
913 directory of the reported object before the callback function is called.
914 When @code{ntfw} finally returns the current directory is restored to
915 its original value.
916 @item FTW_DEPTH
917 If this option is specified then all subdirectories and files within
918 them are processed before processing the top directory itself
919 (depth-first processing).  This also means the type flag given to the
920 callback function is @code{FTW_DP} and not @code{FTW_D}.
921 @item FTW_ACTIONRETVAL
922 If this option is specified then return values from callbacks
923 are handled differently.  If the callback returns @code{FTW_CONTINUE},
924 walking continues normally.  @code{FTW_STOP} means walking stops
925 and @code{FTW_STOP} is returned to the caller.  If @code{FTW_SKIP_SUBTREE}
926 is returned by the callback with @code{FTW_D} argument, the subtree
927 is skipped and walking continues with next sibling of the directory.
928 If @code{FTW_SKIP_SIBLINGS} is returned by the callback, all siblings
929 of the current entry are skipped and walking continues in its parent.
930 No other return values should be returned from the callbacks if
931 this option is set.  This option is a GNU extension.
932 @end vtable
934 The return value is computed in the same way as for @code{ftw}.
935 @code{nftw} returns @math{0} if no failures occurred and all callback
936 functions returned @math{0}.  In case of internal errors, such as memory
937 problems, the return value is @math{-1} and @var{errno} is set
938 accordingly.  If the return value of a callback invocation was non-zero
939 then that value is returned.
941 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
942 32-bit system this function is in fact @code{nftw64}, i.e. the LFS
943 interface transparently replaces the old interface.
944 @end deftypefun
946 @comment ftw.h
947 @comment Unix98
948 @deftypefun int nftw64 (const char *@var{filename}, __nftw64_func_t @var{func}, int @var{descriptors}, int @var{flag})
949 This function is similar to @code{nftw} but it can work on filesystems
950 with large files.  File information is reported using a variable of type
951 @code{struct stat64} which is passed by reference to the callback
952 function.
954 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
955 32-bit system this function is available under the name @code{nftw} and
956 transparently replaces the old implementation.
957 @end deftypefun
960 @node Hard Links
961 @section Hard Links
962 @cindex hard link
963 @cindex link, hard
964 @cindex multiple names for one file
965 @cindex file names, multiple
967 In POSIX systems, one file can have many names at the same time.  All of
968 the names are equally real, and no one of them is preferred to the
969 others.
971 To add a name to a file, use the @code{link} function.  (The new name is
972 also called a @dfn{hard link} to the file.)  Creating a new link to a
973 file does not copy the contents of the file; it simply makes a new name
974 by which the file can be known, in addition to the file's existing name
975 or names.
977 One file can have names in several directories, so the organization
978 of the file system is not a strict hierarchy or tree.
980 In most implementations, it is not possible to have hard links to the
981 same file in multiple file systems.  @code{link} reports an error if you
982 try to make a hard link to the file from another file system when this
983 cannot be done.
985 The prototype for the @code{link} function is declared in the header
986 file @file{unistd.h}.
987 @pindex unistd.h
989 @comment unistd.h
990 @comment POSIX.1
991 @deftypefun int link (const char *@var{oldname}, const char *@var{newname})
992 The @code{link} function makes a new link to the existing file named by
993 @var{oldname}, under the new name @var{newname}.
995 This function returns a value of @code{0} if it is successful and
996 @code{-1} on failure.  In addition to the usual file name errors
997 (@pxref{File Name Errors}) for both @var{oldname} and @var{newname}, the
998 following @code{errno} error conditions are defined for this function:
1000 @table @code
1001 @item EACCES
1002 You are not allowed to write to the directory in which the new link is
1003 to be written.
1004 @ignore
1005 Some implementations also require that the existing file be accessible
1006 by the caller, and use this error to report failure for that reason.
1007 @end ignore
1009 @item EEXIST
1010 There is already a file named @var{newname}.  If you want to replace
1011 this link with a new link, you must remove the old link explicitly first.
1013 @item EMLINK
1014 There are already too many links to the file named by @var{oldname}.
1015 (The maximum number of links to a file is @w{@code{LINK_MAX}}; see
1016 @ref{Limits for Files}.)
1018 @item ENOENT
1019 The file named by @var{oldname} doesn't exist.  You can't make a link to
1020 a file that doesn't exist.
1022 @item ENOSPC
1023 The directory or file system that would contain the new link is full
1024 and cannot be extended.
1026 @item EPERM
1027 In the GNU system and some others, you cannot make links to directories.
1028 Many systems allow only privileged users to do so.  This error
1029 is used to report the problem.
1031 @item EROFS
1032 The directory containing the new link can't be modified because it's on
1033 a read-only file system.
1035 @item EXDEV
1036 The directory specified in @var{newname} is on a different file system
1037 than the existing file.
1039 @item EIO
1040 A hardware error occurred while trying to read or write the to filesystem.
1041 @end table
1042 @end deftypefun
1044 @node Symbolic Links
1045 @section Symbolic Links
1046 @cindex soft link
1047 @cindex link, soft
1048 @cindex symbolic link
1049 @cindex link, symbolic
1051 The GNU system supports @dfn{soft links} or @dfn{symbolic links}.  This
1052 is a kind of ``file'' that is essentially a pointer to another file
1053 name.  Unlike hard links, symbolic links can be made to directories or
1054 across file systems with no restrictions.  You can also make a symbolic
1055 link to a name which is not the name of any file.  (Opening this link
1056 will fail until a file by that name is created.)  Likewise, if the
1057 symbolic link points to an existing file which is later deleted, the
1058 symbolic link continues to point to the same file name even though the
1059 name no longer names any file.
1061 The reason symbolic links work the way they do is that special things
1062 happen when you try to open the link.  The @code{open} function realizes
1063 you have specified the name of a link, reads the file name contained in
1064 the link, and opens that file name instead.  The @code{stat} function
1065 likewise operates on the file that the symbolic link points to, instead
1066 of on the link itself.
1068 By contrast, other operations such as deleting or renaming the file
1069 operate on the link itself.  The functions @code{readlink} and
1070 @code{lstat} also refrain from following symbolic links, because their
1071 purpose is to obtain information about the link.  @code{link}, the
1072 function that makes a hard link, does too.  It makes a hard link to the
1073 symbolic link, which one rarely wants.
1075 Some systems have for some functions operating on files have a limit on
1076 how many symbolic links are followed when resolving a path name.  The
1077 limit if it exists is published in the @file{sys/param.h} header file.
1079 @comment sys/param.h
1080 @comment BSD
1081 @deftypevr Macro int MAXSYMLINKS
1083 The macro @code{MAXSYMLINKS} specifies how many symlinks some function
1084 will follow before returning @code{ELOOP}.  Not all functions behave the
1085 same and this value is not the same a that returned for
1086 @code{_SC_SYMLOOP} by @code{sysconf}.  In fact, the @code{sysconf}
1087 result can indicate that there is no fixed limit although
1088 @code{MAXSYMLINKS} exists and has a finite value.
1089 @end deftypevr
1091 Prototypes for most of the functions listed in this section are in
1092 @file{unistd.h}.
1093 @pindex unistd.h
1095 @comment unistd.h
1096 @comment BSD
1097 @deftypefun int symlink (const char *@var{oldname}, const char *@var{newname})
1098 The @code{symlink} function makes a symbolic link to @var{oldname} named
1099 @var{newname}.
1101 The normal return value from @code{symlink} is @code{0}.  A return value
1102 of @code{-1} indicates an error.  In addition to the usual file name
1103 syntax errors (@pxref{File Name Errors}), the following @code{errno}
1104 error conditions are defined for this function:
1106 @table @code
1107 @item EEXIST
1108 There is already an existing file named @var{newname}.
1110 @item EROFS
1111 The file @var{newname} would exist on a read-only file system.
1113 @item ENOSPC
1114 The directory or file system cannot be extended to make the new link.
1116 @item EIO
1117 A hardware error occurred while reading or writing data on the disk.
1119 @ignore
1120 @comment not sure about these
1121 @item ELOOP
1122 There are too many levels of indirection.  This can be the result of
1123 circular symbolic links to directories.
1125 @item EDQUOT
1126 The new link can't be created because the user's disk quota has been
1127 exceeded.
1128 @end ignore
1129 @end table
1130 @end deftypefun
1132 @comment unistd.h
1133 @comment BSD
1134 @deftypefun int readlink (const char *@var{filename}, char *@var{buffer}, size_t @var{size})
1135 The @code{readlink} function gets the value of the symbolic link
1136 @var{filename}.  The file name that the link points to is copied into
1137 @var{buffer}.  This file name string is @emph{not} null-terminated;
1138 @code{readlink} normally returns the number of characters copied.  The
1139 @var{size} argument specifies the maximum number of characters to copy,
1140 usually the allocation size of @var{buffer}.
1142 If the return value equals @var{size}, you cannot tell whether or not
1143 there was room to return the entire name.  So make a bigger buffer and
1144 call @code{readlink} again.  Here is an example:
1146 @smallexample
1147 char *
1148 readlink_malloc (const char *filename)
1150   int size = 100;
1151   char *buffer = NULL;
1153   while (1)
1154     @{
1155       buffer = (char *) xrealloc (buffer, size);
1156       int nchars = readlink (filename, buffer, size);
1157       if (nchars < 0)
1158         @{
1159           free (buffer);
1160           return NULL;
1161         @}
1162       if (nchars < size)
1163         return buffer;
1164       size *= 2;
1165     @}
1167 @end smallexample
1169 @c @group  Invalid outside example.
1170 A value of @code{-1} is returned in case of error.  In addition to the
1171 usual file name errors (@pxref{File Name Errors}), the following
1172 @code{errno} error conditions are defined for this function:
1174 @table @code
1175 @item EINVAL
1176 The named file is not a symbolic link.
1178 @item EIO
1179 A hardware error occurred while reading or writing data on the disk.
1180 @end table
1181 @c @end group
1182 @end deftypefun
1184 In some situations it is desirable to resolve all the
1185 symbolic links to get the real
1186 name of a file where no prefix names a symbolic link which is followed
1187 and no filename in the path is @code{.} or @code{..}.  This is for
1188 instance desirable if files have to be compare in which case different
1189 names can refer to the same inode.
1191 @comment stdlib.h
1192 @comment GNU
1193 @deftypefun {char *} canonicalize_file_name (const char *@var{name})
1195 The @code{canonicalize_file_name} function returns the absolute name of
1196 the file named by @var{name} which contains no @code{.}, @code{..}
1197 components nor any repeated path separators (@code{/}) or symlinks.  The
1198 result is passed back as the return value of the function in a block of
1199 memory allocated with @code{malloc}.  If the result is not used anymore
1200 the memory should be freed with a call to @code{free}.
1202 In any of the path components except the last one is missing the
1203 function returns a NULL pointer.  This is also what is returned if the
1204 length of the path reaches or exceeds @code{PATH_MAX} characters.  In
1205 any case @code{errno} is set accordingly.
1207 @table @code
1208 @item ENAMETOOLONG
1209 The resulting path is too long.  This error only occurs on systems which
1210 have a limit on the file name length.
1212 @item EACCES
1213 At least one of the path components is not readable.
1215 @item ENOENT
1216 The input file name is empty.
1218 @item ENOENT
1219 At least one of the path components does not exist.
1221 @item ELOOP
1222 More than @code{MAXSYMLINKS} many symlinks have been followed.
1223 @end table
1225 This function is a GNU extension and is declared in @file{stdlib.h}.
1226 @end deftypefun
1228 The Unix standard includes a similar function which differs from
1229 @code{canonicalize_file_name} in that the user has to provide the buffer
1230 where the result is placed in.
1232 @comment stdlib.h
1233 @comment XPG
1234 @deftypefun {char *} realpath (const char *restrict @var{name}, char *restrict @var{resolved})
1236 A call to @code{realpath} where the @var{resolved} parameter is
1237 @code{NULL} behaves exactly like @code{canonicalize_file_name}.  The
1238 function allocates a buffer for the file name and returns a pointer to
1239 it.  If @var{resolved} is not @code{NULL} it points to a buffer into
1240 which the result is copied.  It is the callers responsibility to
1241 allocate a buffer which is large enough.  On systems which define
1242 @code{PATH_MAX} this means the buffer must be large enough for a
1243 pathname of this size.  For systems without limitations on the pathname
1244 length the requirement cannot be met and programs should not call
1245 @code{realpath} with anything but @code{NULL} for the second parameter.
1247 One other difference is that the buffer @var{resolved} (if nonzero) will
1248 contain the part of the path component which does not exist or is not
1249 readable if the function returns @code{NULL} and @code{errno} is set to
1250 @code{EACCES} or @code{ENOENT}.
1252 This function is declared in @file{stdlib.h}.
1253 @end deftypefun
1255 The advantage of using this function is that it is more widely
1256 available.  The drawback is that it reports failures for long path on
1257 systems which have no limits on the file name length.
1259 @node Deleting Files
1260 @section Deleting Files
1261 @cindex deleting a file
1262 @cindex removing a file
1263 @cindex unlinking a file
1265 You can delete a file with @code{unlink} or @code{remove}.
1267 Deletion actually deletes a file name.  If this is the file's only name,
1268 then the file is deleted as well.  If the file has other remaining names
1269 (@pxref{Hard Links}), it remains accessible under those names.
1271 @comment unistd.h
1272 @comment POSIX.1
1273 @deftypefun int unlink (const char *@var{filename})
1274 The @code{unlink} function deletes the file name @var{filename}.  If
1275 this is a file's sole name, the file itself is also deleted.  (Actually,
1276 if any process has the file open when this happens, deletion is
1277 postponed until all processes have closed the file.)
1279 @pindex unistd.h
1280 The function @code{unlink} is declared in the header file @file{unistd.h}.
1282 This function returns @code{0} on successful completion, and @code{-1}
1283 on error.  In addition to the usual file name errors
1284 (@pxref{File Name Errors}), the following @code{errno} error conditions are
1285 defined for this function:
1287 @table @code
1288 @item EACCES
1289 Write permission is denied for the directory from which the file is to be
1290 removed, or the directory has the sticky bit set and you do not own the file.
1292 @item EBUSY
1293 This error indicates that the file is being used by the system in such a
1294 way that it can't be unlinked.  For example, you might see this error if
1295 the file name specifies the root directory or a mount point for a file
1296 system.
1298 @item ENOENT
1299 The file name to be deleted doesn't exist.
1301 @item EPERM
1302 On some systems @code{unlink} cannot be used to delete the name of a
1303 directory, or at least can only be used this way by a privileged user.
1304 To avoid such problems, use @code{rmdir} to delete directories.  (In the
1305 GNU system @code{unlink} can never delete the name of a directory.)
1307 @item EROFS
1308 The directory containing the file name to be deleted is on a read-only
1309 file system and can't be modified.
1310 @end table
1311 @end deftypefun
1313 @comment unistd.h
1314 @comment POSIX.1
1315 @deftypefun int rmdir (const char *@var{filename})
1316 @cindex directories, deleting
1317 @cindex deleting a directory
1318 The @code{rmdir} function deletes a directory.  The directory must be
1319 empty before it can be removed; in other words, it can only contain
1320 entries for @file{.} and @file{..}.
1322 In most other respects, @code{rmdir} behaves like @code{unlink}.  There
1323 are two additional @code{errno} error conditions defined for
1324 @code{rmdir}:
1326 @table @code
1327 @item ENOTEMPTY
1328 @itemx EEXIST
1329 The directory to be deleted is not empty.
1330 @end table
1332 These two error codes are synonymous; some systems use one, and some use
1333 the other.  The GNU system always uses @code{ENOTEMPTY}.
1335 The prototype for this function is declared in the header file
1336 @file{unistd.h}.
1337 @pindex unistd.h
1338 @end deftypefun
1340 @comment stdio.h
1341 @comment ISO
1342 @deftypefun int remove (const char *@var{filename})
1343 This is the @w{ISO C} function to remove a file.  It works like
1344 @code{unlink} for files and like @code{rmdir} for directories.
1345 @code{remove} is declared in @file{stdio.h}.
1346 @pindex stdio.h
1347 @end deftypefun
1349 @node Renaming Files
1350 @section Renaming Files
1352 The @code{rename} function is used to change a file's name.
1354 @cindex renaming a file
1355 @comment stdio.h
1356 @comment ISO
1357 @deftypefun int rename (const char *@var{oldname}, const char *@var{newname})
1358 The @code{rename} function renames the file @var{oldname} to
1359 @var{newname}.  The file formerly accessible under the name
1360 @var{oldname} is afterwards accessible as @var{newname} instead.  (If
1361 the file had any other names aside from @var{oldname}, it continues to
1362 have those names.)
1364 The directory containing the name @var{newname} must be on the same file
1365 system as the directory containing the name @var{oldname}.
1367 One special case for @code{rename} is when @var{oldname} and
1368 @var{newname} are two names for the same file.  The consistent way to
1369 handle this case is to delete @var{oldname}.  However, in this case
1370 POSIX requires that @code{rename} do nothing and report success---which
1371 is inconsistent.  We don't know what your operating system will do.
1373 If @var{oldname} is not a directory, then any existing file named
1374 @var{newname} is removed during the renaming operation.  However, if
1375 @var{newname} is the name of a directory, @code{rename} fails in this
1376 case.
1378 If @var{oldname} is a directory, then either @var{newname} must not
1379 exist or it must name a directory that is empty.  In the latter case,
1380 the existing directory named @var{newname} is deleted first.  The name
1381 @var{newname} must not specify a subdirectory of the directory
1382 @code{oldname} which is being renamed.
1384 One useful feature of @code{rename} is that the meaning of @var{newname}
1385 changes ``atomically'' from any previously existing file by that name to
1386 its new meaning (i.e. the file that was called @var{oldname}).  There is
1387 no instant at which @var{newname} is non-existent ``in between'' the old
1388 meaning and the new meaning.  If there is a system crash during the
1389 operation, it is possible for both names to still exist; but
1390 @var{newname} will always be intact if it exists at all.
1392 If @code{rename} fails, it returns @code{-1}.  In addition to the usual
1393 file name errors (@pxref{File Name Errors}), the following
1394 @code{errno} error conditions are defined for this function:
1396 @table @code
1397 @item EACCES
1398 One of the directories containing @var{newname} or @var{oldname}
1399 refuses write permission; or @var{newname} and @var{oldname} are
1400 directories and write permission is refused for one of them.
1402 @item EBUSY
1403 A directory named by @var{oldname} or @var{newname} is being used by
1404 the system in a way that prevents the renaming from working.  This includes
1405 directories that are mount points for filesystems, and directories
1406 that are the current working directories of processes.
1408 @item ENOTEMPTY
1409 @itemx EEXIST
1410 The directory @var{newname} isn't empty.  The GNU system always returns
1411 @code{ENOTEMPTY} for this, but some other systems return @code{EEXIST}.
1413 @item EINVAL
1414 @var{oldname} is a directory that contains @var{newname}.
1416 @item EISDIR
1417 @var{newname} is a directory but the @var{oldname} isn't.
1419 @item EMLINK
1420 The parent directory of @var{newname} would have too many links
1421 (entries).
1423 @item ENOENT
1424 The file @var{oldname} doesn't exist.
1426 @item ENOSPC
1427 The directory that would contain @var{newname} has no room for another
1428 entry, and there is no space left in the file system to expand it.
1430 @item EROFS
1431 The operation would involve writing to a directory on a read-only file
1432 system.
1434 @item EXDEV
1435 The two file names @var{newname} and @var{oldname} are on different
1436 file systems.
1437 @end table
1438 @end deftypefun
1440 @node Creating Directories
1441 @section Creating Directories
1442 @cindex creating a directory
1443 @cindex directories, creating
1445 @pindex mkdir
1446 Directories are created with the @code{mkdir} function.  (There is also
1447 a shell command @code{mkdir} which does the same thing.)
1448 @c !!! umask
1450 @comment sys/stat.h
1451 @comment POSIX.1
1452 @deftypefun int mkdir (const char *@var{filename}, mode_t @var{mode})
1453 The @code{mkdir} function creates a new, empty directory with name
1454 @var{filename}.
1456 The argument @var{mode} specifies the file permissions for the new
1457 directory file.  @xref{Permission Bits}, for more information about
1458 this.
1460 A return value of @code{0} indicates successful completion, and
1461 @code{-1} indicates failure.  In addition to the usual file name syntax
1462 errors (@pxref{File Name Errors}), the following @code{errno} error
1463 conditions are defined for this function:
1465 @table @code
1466 @item EACCES
1467 Write permission is denied for the parent directory in which the new
1468 directory is to be added.
1470 @item EEXIST
1471 A file named @var{filename} already exists.
1473 @item EMLINK
1474 The parent directory has too many links (entries).
1476 Well-designed file systems never report this error, because they permit
1477 more links than your disk could possibly hold.  However, you must still
1478 take account of the possibility of this error, as it could result from
1479 network access to a file system on another machine.
1481 @item ENOSPC
1482 The file system doesn't have enough room to create the new directory.
1484 @item EROFS
1485 The parent directory of the directory being created is on a read-only
1486 file system and cannot be modified.
1487 @end table
1489 To use this function, your program should include the header file
1490 @file{sys/stat.h}.
1491 @pindex sys/stat.h
1492 @end deftypefun
1494 @node File Attributes
1495 @section File Attributes
1497 @pindex ls
1498 When you issue an @samp{ls -l} shell command on a file, it gives you
1499 information about the size of the file, who owns it, when it was last
1500 modified, etc.  These are called the @dfn{file attributes}, and are
1501 associated with the file itself and not a particular one of its names.
1503 This section contains information about how you can inquire about and
1504 modify the attributes of a file.
1506 @menu
1507 * Attribute Meanings::          The names of the file attributes,
1508                                  and what their values mean.
1509 * Reading Attributes::          How to read the attributes of a file.
1510 * Testing File Type::           Distinguishing ordinary files,
1511                                  directories, links@dots{}
1512 * File Owner::                  How ownership for new files is determined,
1513                                  and how to change it.
1514 * Permission Bits::             How information about a file's access
1515                                  mode is stored.
1516 * Access Permission::           How the system decides who can access a file.
1517 * Setting Permissions::         How permissions for new files are assigned,
1518                                  and how to change them.
1519 * Testing File Access::         How to find out if your process can
1520                                  access a file.
1521 * File Times::                  About the time attributes of a file.
1522 * File Size::                   Manually changing the size of a file.
1523 @end menu
1525 @node Attribute Meanings
1526 @subsection The meaning of the File Attributes
1527 @cindex status of a file
1528 @cindex attributes of a file
1529 @cindex file attributes
1531 When you read the attributes of a file, they come back in a structure
1532 called @code{struct stat}.  This section describes the names of the
1533 attributes, their data types, and what they mean.  For the functions
1534 to read the attributes of a file, see @ref{Reading Attributes}.
1536 The header file @file{sys/stat.h} declares all the symbols defined
1537 in this section.
1538 @pindex sys/stat.h
1540 @comment sys/stat.h
1541 @comment POSIX.1
1542 @deftp {Data Type} {struct stat}
1543 The @code{stat} structure type is used to return information about the
1544 attributes of a file.  It contains at least the following members:
1546 @table @code
1547 @item mode_t st_mode
1548 Specifies the mode of the file.  This includes file type information
1549 (@pxref{Testing File Type}) and the file permission bits
1550 (@pxref{Permission Bits}).
1552 @item ino_t st_ino
1553 The file serial number, which distinguishes this file from all other
1554 files on the same device.
1556 @item dev_t st_dev
1557 Identifies the device containing the file.  The @code{st_ino} and
1558 @code{st_dev}, taken together, uniquely identify the file.  The
1559 @code{st_dev} value is not necessarily consistent across reboots or
1560 system crashes, however.
1562 @item nlink_t st_nlink
1563 The number of hard links to the file.  This count keeps track of how
1564 many directories have entries for this file.  If the count is ever
1565 decremented to zero, then the file itself is discarded as soon as no
1566 process still holds it open.  Symbolic links are not counted in the
1567 total.
1569 @item uid_t st_uid
1570 The user ID of the file's owner.  @xref{File Owner}.
1572 @item gid_t st_gid
1573 The group ID of the file.  @xref{File Owner}.
1575 @item off_t st_size
1576 This specifies the size of a regular file in bytes.  For files that are
1577 really devices this field isn't usually meaningful.  For symbolic links
1578 this specifies the length of the file name the link refers to.
1580 @item time_t st_atime
1581 This is the last access time for the file.  @xref{File Times}.
1583 @item unsigned long int st_atime_usec
1584 This is the fractional part of the last access time for the file.
1585 @xref{File Times}.
1587 @item time_t st_mtime
1588 This is the time of the last modification to the contents of the file.
1589 @xref{File Times}.
1591 @item unsigned long int st_mtime_usec
1592 This is the fractional part of the time of the last modification to the
1593 contents of the file.  @xref{File Times}.
1595 @item time_t st_ctime
1596 This is the time of the last modification to the attributes of the file.
1597 @xref{File Times}.
1599 @item unsigned long int st_ctime_usec
1600 This is the fractional part of the time of the last modification to the
1601 attributes of the file.  @xref{File Times}.
1603 @c !!! st_rdev
1604 @item blkcnt_t st_blocks
1605 This is the amount of disk space that the file occupies, measured in
1606 units of 512-byte blocks.
1608 The number of disk blocks is not strictly proportional to the size of
1609 the file, for two reasons: the file system may use some blocks for
1610 internal record keeping; and the file may be sparse---it may have
1611 ``holes'' which contain zeros but do not actually take up space on the
1612 disk.
1614 You can tell (approximately) whether a file is sparse by comparing this
1615 value with @code{st_size}, like this:
1617 @smallexample
1618 (st.st_blocks * 512 < st.st_size)
1619 @end smallexample
1621 This test is not perfect because a file that is just slightly sparse
1622 might not be detected as sparse at all.  For practical applications,
1623 this is not a problem.
1625 @item unsigned int st_blksize
1626 The optimal block size for reading of writing this file, in bytes.  You
1627 might use this size for allocating the buffer space for reading of
1628 writing the file.  (This is unrelated to @code{st_blocks}.)
1629 @end table
1630 @end deftp
1632 The extensions for the Large File Support (LFS) require, even on 32-bit
1633 machines, types which can handle file sizes up to @math{2^63}.
1634 Therefore a new definition of @code{struct stat} is necessary.
1636 @comment sys/stat.h
1637 @comment LFS
1638 @deftp {Data Type} {struct stat64}
1639 The members of this type are the same and have the same names as those
1640 in @code{struct stat}.  The only difference is that the members
1641 @code{st_ino}, @code{st_size}, and @code{st_blocks} have a different
1642 type to support larger values.
1644 @table @code
1645 @item mode_t st_mode
1646 Specifies the mode of the file.  This includes file type information
1647 (@pxref{Testing File Type}) and the file permission bits
1648 (@pxref{Permission Bits}).
1650 @item ino64_t st_ino
1651 The file serial number, which distinguishes this file from all other
1652 files on the same device.
1654 @item dev_t st_dev
1655 Identifies the device containing the file.  The @code{st_ino} and
1656 @code{st_dev}, taken together, uniquely identify the file.  The
1657 @code{st_dev} value is not necessarily consistent across reboots or
1658 system crashes, however.
1660 @item nlink_t st_nlink
1661 The number of hard links to the file.  This count keeps track of how
1662 many directories have entries for this file.  If the count is ever
1663 decremented to zero, then the file itself is discarded as soon as no
1664 process still holds it open.  Symbolic links are not counted in the
1665 total.
1667 @item uid_t st_uid
1668 The user ID of the file's owner.  @xref{File Owner}.
1670 @item gid_t st_gid
1671 The group ID of the file.  @xref{File Owner}.
1673 @item off64_t st_size
1674 This specifies the size of a regular file in bytes.  For files that are
1675 really devices this field isn't usually meaningful.  For symbolic links
1676 this specifies the length of the file name the link refers to.
1678 @item time_t st_atime
1679 This is the last access time for the file.  @xref{File Times}.
1681 @item unsigned long int st_atime_usec
1682 This is the fractional part of the last access time for the file.
1683 @xref{File Times}.
1685 @item time_t st_mtime
1686 This is the time of the last modification to the contents of the file.
1687 @xref{File Times}.
1689 @item unsigned long int st_mtime_usec
1690 This is the fractional part of the time of the last modification to the
1691 contents of the file.  @xref{File Times}.
1693 @item time_t st_ctime
1694 This is the time of the last modification to the attributes of the file.
1695 @xref{File Times}.
1697 @item unsigned long int st_ctime_usec
1698 This is the fractional part of the time of the last modification to the
1699 attributes of the file.  @xref{File Times}.
1701 @c !!! st_rdev
1702 @item blkcnt64_t st_blocks
1703 This is the amount of disk space that the file occupies, measured in
1704 units of 512-byte blocks.
1706 @item unsigned int st_blksize
1707 The optimal block size for reading of writing this file, in bytes.  You
1708 might use this size for allocating the buffer space for reading of
1709 writing the file.  (This is unrelated to @code{st_blocks}.)
1710 @end table
1711 @end deftp
1713 Some of the file attributes have special data type names which exist
1714 specifically for those attributes.  (They are all aliases for well-known
1715 integer types that you know and love.)  These typedef names are defined
1716 in the header file @file{sys/types.h} as well as in @file{sys/stat.h}.
1717 Here is a list of them.
1719 @comment sys/types.h
1720 @comment POSIX.1
1721 @deftp {Data Type} mode_t
1722 This is an integer data type used to represent file modes.  In the
1723 GNU system, this is equivalent to @code{unsigned int}.
1724 @end deftp
1726 @cindex inode number
1727 @comment sys/types.h
1728 @comment POSIX.1
1729 @deftp {Data Type} ino_t
1730 This is an arithmetic data type used to represent file serial numbers.
1731 (In Unix jargon, these are sometimes called @dfn{inode numbers}.)
1732 In the GNU system, this type is equivalent to @code{unsigned long int}.
1734 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1735 is transparently replaced by @code{ino64_t}.
1736 @end deftp
1738 @comment sys/types.h
1739 @comment Unix98
1740 @deftp {Data Type} ino64_t
1741 This is an arithmetic data type used to represent file serial numbers
1742 for the use in LFS.  In the GNU system, this type is equivalent to
1743 @code{unsigned long longint}.
1745 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1746 available under the name @code{ino_t}.
1747 @end deftp
1749 @comment sys/types.h
1750 @comment POSIX.1
1751 @deftp {Data Type} dev_t
1752 This is an arithmetic data type used to represent file device numbers.
1753 In the GNU system, this is equivalent to @code{int}.
1754 @end deftp
1756 @comment sys/types.h
1757 @comment POSIX.1
1758 @deftp {Data Type} nlink_t
1759 This is an arithmetic data type used to represent file link counts.
1760 In the GNU system, this is equivalent to @code{unsigned short int}.
1761 @end deftp
1763 @comment sys/types.h
1764 @comment Unix98
1765 @deftp {Data Type} blkcnt_t
1766 This is an arithmetic data type used to represent block counts.
1767 In the GNU system, this is equivalent to @code{unsigned long int}.
1769 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1770 is transparently replaced by @code{blkcnt64_t}.
1771 @end deftp
1773 @comment sys/types.h
1774 @comment Unix98
1775 @deftp {Data Type} blkcnt64_t
1776 This is an arithmetic data type used to represent block counts for the
1777 use in LFS.  In the GNU system, this is equivalent to @code{unsigned
1778 long long int}.
1780 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1781 available under the name @code{blkcnt_t}.
1782 @end deftp
1784 @node Reading Attributes
1785 @subsection Reading the Attributes of a File
1787 To examine the attributes of files, use the functions @code{stat},
1788 @code{fstat} and @code{lstat}.  They return the attribute information in
1789 a @code{struct stat} object.  All three functions are declared in the
1790 header file @file{sys/stat.h}.
1792 @comment sys/stat.h
1793 @comment POSIX.1
1794 @deftypefun int stat (const char *@var{filename}, struct stat *@var{buf})
1795 The @code{stat} function returns information about the attributes of the
1796 file named by @w{@var{filename}} in the structure pointed to by @var{buf}.
1798 If @var{filename} is the name of a symbolic link, the attributes you get
1799 describe the file that the link points to.  If the link points to a
1800 nonexistent file name, then @code{stat} fails reporting a nonexistent
1801 file.
1803 The return value is @code{0} if the operation is successful, or
1804 @code{-1} on failure.  In addition to the usual file name errors
1805 (@pxref{File Name Errors}, the following @code{errno} error conditions
1806 are defined for this function:
1808 @table @code
1809 @item ENOENT
1810 The file named by @var{filename} doesn't exist.
1811 @end table
1813 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1814 function is in fact @code{stat64} since the LFS interface transparently
1815 replaces the normal implementation.
1816 @end deftypefun
1818 @comment sys/stat.h
1819 @comment Unix98
1820 @deftypefun int stat64 (const char *@var{filename}, struct stat64 *@var{buf})
1821 This function is similar to @code{stat} but it is also able to work on
1822 files larger then @math{2^31} bytes on 32-bit systems.  To be able to do
1823 this the result is stored in a variable of type @code{struct stat64} to
1824 which @var{buf} must point.
1826 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1827 function is available under the name @code{stat} and so transparently
1828 replaces the interface for small files on 32-bit machines.
1829 @end deftypefun
1831 @comment sys/stat.h
1832 @comment POSIX.1
1833 @deftypefun int fstat (int @var{filedes}, struct stat *@var{buf})
1834 The @code{fstat} function is like @code{stat}, except that it takes an
1835 open file descriptor as an argument instead of a file name.
1836 @xref{Low-Level I/O}.
1838 Like @code{stat}, @code{fstat} returns @code{0} on success and @code{-1}
1839 on failure.  The following @code{errno} error conditions are defined for
1840 @code{fstat}:
1842 @table @code
1843 @item EBADF
1844 The @var{filedes} argument is not a valid file descriptor.
1845 @end table
1847 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1848 function is in fact @code{fstat64} since the LFS interface transparently
1849 replaces the normal implementation.
1850 @end deftypefun
1852 @comment sys/stat.h
1853 @comment Unix98
1854 @deftypefun int fstat64 (int @var{filedes}, struct stat64 *@var{buf})
1855 This function is similar to @code{fstat} but is able to work on large
1856 files on 32-bit platforms.  For large files the file descriptor
1857 @var{filedes} should be obtained by @code{open64} or @code{creat64}.
1858 The @var{buf} pointer points to a variable of type @code{struct stat64}
1859 which is able to represent the larger values.
1861 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1862 function is available under the name @code{fstat} and so transparently
1863 replaces the interface for small files on 32-bit machines.
1864 @end deftypefun
1866 @comment sys/stat.h
1867 @comment BSD
1868 @deftypefun int lstat (const char *@var{filename}, struct stat *@var{buf})
1869 The @code{lstat} function is like @code{stat}, except that it does not
1870 follow symbolic links.  If @var{filename} is the name of a symbolic
1871 link, @code{lstat} returns information about the link itself; otherwise
1872 @code{lstat} works like @code{stat}.  @xref{Symbolic Links}.
1874 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1875 function is in fact @code{lstat64} since the LFS interface transparently
1876 replaces the normal implementation.
1877 @end deftypefun
1879 @comment sys/stat.h
1880 @comment Unix98
1881 @deftypefun int lstat64 (const char *@var{filename}, struct stat64 *@var{buf})
1882 This function is similar to @code{lstat} but it is also able to work on
1883 files larger then @math{2^31} bytes on 32-bit systems.  To be able to do
1884 this the result is stored in a variable of type @code{struct stat64} to
1885 which @var{buf} must point.
1887 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1888 function is available under the name @code{lstat} and so transparently
1889 replaces the interface for small files on 32-bit machines.
1890 @end deftypefun
1892 @node Testing File Type
1893 @subsection Testing the Type of a File
1895 The @dfn{file mode}, stored in the @code{st_mode} field of the file
1896 attributes, contains two kinds of information: the file type code, and
1897 the access permission bits.  This section discusses only the type code,
1898 which you can use to tell whether the file is a directory, socket,
1899 symbolic link, and so on.  For details about access permissions see
1900 @ref{Permission Bits}.
1902 There are two ways you can access the file type information in a file
1903 mode.  Firstly, for each file type there is a @dfn{predicate macro}
1904 which examines a given file mode and returns whether it is of that type
1905 or not.  Secondly, you can mask out the rest of the file mode to leave
1906 just the file type code, and compare this against constants for each of
1907 the supported file types.
1909 All of the symbols listed in this section are defined in the header file
1910 @file{sys/stat.h}.
1911 @pindex sys/stat.h
1913 The following predicate macros test the type of a file, given the value
1914 @var{m} which is the @code{st_mode} field returned by @code{stat} on
1915 that file:
1917 @comment sys/stat.h
1918 @comment POSIX
1919 @deftypefn Macro int S_ISDIR (mode_t @var{m})
1920 This macro returns non-zero if the file is a directory.
1921 @end deftypefn
1923 @comment sys/stat.h
1924 @comment POSIX
1925 @deftypefn Macro int S_ISCHR (mode_t @var{m})
1926 This macro returns non-zero if the file is a character special file (a
1927 device like a terminal).
1928 @end deftypefn
1930 @comment sys/stat.h
1931 @comment POSIX
1932 @deftypefn Macro int S_ISBLK (mode_t @var{m})
1933 This macro returns non-zero if the file is a block special file (a device
1934 like a disk).
1935 @end deftypefn
1937 @comment sys/stat.h
1938 @comment POSIX
1939 @deftypefn Macro int S_ISREG (mode_t @var{m})
1940 This macro returns non-zero if the file is a regular file.
1941 @end deftypefn
1943 @comment sys/stat.h
1944 @comment POSIX
1945 @deftypefn Macro int S_ISFIFO (mode_t @var{m})
1946 This macro returns non-zero if the file is a FIFO special file, or a
1947 pipe.  @xref{Pipes and FIFOs}.
1948 @end deftypefn
1950 @comment sys/stat.h
1951 @comment GNU
1952 @deftypefn Macro int S_ISLNK (mode_t @var{m})
1953 This macro returns non-zero if the file is a symbolic link.
1954 @xref{Symbolic Links}.
1955 @end deftypefn
1957 @comment sys/stat.h
1958 @comment GNU
1959 @deftypefn Macro int S_ISSOCK (mode_t @var{m})
1960 This macro returns non-zero if the file is a socket.  @xref{Sockets}.
1961 @end deftypefn
1963 An alternate non-POSIX method of testing the file type is supported for
1964 compatibility with BSD.  The mode can be bitwise AND-ed with
1965 @code{S_IFMT} to extract the file type code, and compared to the
1966 appropriate constant.  For example,
1968 @smallexample
1969 S_ISCHR (@var{mode})
1970 @end smallexample
1972 @noindent
1973 is equivalent to:
1975 @smallexample
1976 ((@var{mode} & S_IFMT) == S_IFCHR)
1977 @end smallexample
1979 @comment sys/stat.h
1980 @comment BSD
1981 @deftypevr Macro int S_IFMT
1982 This is a bit mask used to extract the file type code from a mode value.
1983 @end deftypevr
1985 These are the symbolic names for the different file type codes:
1987 @table @code
1988 @comment sys/stat.h
1989 @comment BSD
1990 @item S_IFDIR
1991 @vindex S_IFDIR
1992 This is the file type constant of a directory file.
1994 @comment sys/stat.h
1995 @comment BSD
1996 @item S_IFCHR
1997 @vindex S_IFCHR
1998 This is the file type constant of a character-oriented device file.
2000 @comment sys/stat.h
2001 @comment BSD
2002 @item S_IFBLK
2003 @vindex S_IFBLK
2004 This is the file type constant of a block-oriented device file.
2006 @comment sys/stat.h
2007 @comment BSD
2008 @item S_IFREG
2009 @vindex S_IFREG
2010 This is the file type constant of a regular file.
2012 @comment sys/stat.h
2013 @comment BSD
2014 @item S_IFLNK
2015 @vindex S_IFLNK
2016 This is the file type constant of a symbolic link.
2018 @comment sys/stat.h
2019 @comment BSD
2020 @item S_IFSOCK
2021 @vindex S_IFSOCK
2022 This is the file type constant of a socket.
2024 @comment sys/stat.h
2025 @comment BSD
2026 @item S_IFIFO
2027 @vindex S_IFIFO
2028 This is the file type constant of a FIFO or pipe.
2029 @end table
2031 The POSIX.1b standard introduced a few more objects which possibly can
2032 be implemented as object in the filesystem.  These are message queues,
2033 semaphores, and shared memory objects.  To allow differentiating these
2034 objects from other files the POSIX standard introduces three new test
2035 macros.  But unlike the other macros it does not take the value of the
2036 @code{st_mode} field as the parameter.  Instead they expect a pointer to
2037 the whole @code{struct stat} structure.
2039 @comment sys/stat.h
2040 @comment POSIX
2041 @deftypefn Macro int S_TYPEISMQ (struct stat *@var{s})
2042 If the system implement POSIX message queues as distinct objects and the
2043 file is a message queue object, this macro returns a non-zero value.
2044 In all other cases the result is zero.
2045 @end deftypefn
2047 @comment sys/stat.h
2048 @comment POSIX
2049 @deftypefn Macro int S_TYPEISSEM (struct stat *@var{s})
2050 If the system implement POSIX semaphores as distinct objects and the
2051 file is a semaphore object, this macro returns a non-zero value.
2052 In all other cases the result is zero.
2053 @end deftypefn
2055 @comment sys/stat.h
2056 @comment POSIX
2057 @deftypefn Macro int S_TYPEISSHM (struct stat *@var{s})
2058 If the system implement POSIX shared memory objects as distinct objects
2059 and the file is an shared memory object, this macro returns a non-zero
2060 value.  In all other cases the result is zero.
2061 @end deftypefn
2063 @node File Owner
2064 @subsection File Owner
2065 @cindex file owner
2066 @cindex owner of a file
2067 @cindex group owner of a file
2069 Every file has an @dfn{owner} which is one of the registered user names
2070 defined on the system.  Each file also has a @dfn{group} which is one of
2071 the defined groups.  The file owner can often be useful for showing you
2072 who edited the file (especially when you edit with GNU Emacs), but its
2073 main purpose is for access control.
2075 The file owner and group play a role in determining access because the
2076 file has one set of access permission bits for the owner, another set
2077 that applies to users who belong to the file's group, and a third set of
2078 bits that applies to everyone else.  @xref{Access Permission}, for the
2079 details of how access is decided based on this data.
2081 When a file is created, its owner is set to the effective user ID of the
2082 process that creates it (@pxref{Process Persona}).  The file's group ID
2083 may be set to either the effective group ID of the process, or the group
2084 ID of the directory that contains the file, depending on the system
2085 where the file is stored.  When you access a remote file system, it
2086 behaves according to its own rules, not according to the system your
2087 program is running on.  Thus, your program must be prepared to encounter
2088 either kind of behavior no matter what kind of system you run it on.
2090 @pindex chown
2091 @pindex chgrp
2092 You can change the owner and/or group owner of an existing file using
2093 the @code{chown} function.  This is the primitive for the @code{chown}
2094 and @code{chgrp} shell commands.
2096 @pindex unistd.h
2097 The prototype for this function is declared in @file{unistd.h}.
2099 @comment unistd.h
2100 @comment POSIX.1
2101 @deftypefun int chown (const char *@var{filename}, uid_t @var{owner}, gid_t @var{group})
2102 The @code{chown} function changes the owner of the file @var{filename} to
2103 @var{owner}, and its group owner to @var{group}.
2105 Changing the owner of the file on certain systems clears the set-user-ID
2106 and set-group-ID permission bits.  (This is because those bits may not
2107 be appropriate for the new owner.)  Other file permission bits are not
2108 changed.
2110 The return value is @code{0} on success and @code{-1} on failure.
2111 In addition to the usual file name errors (@pxref{File Name Errors}),
2112 the following @code{errno} error conditions are defined for this function:
2114 @table @code
2115 @item EPERM
2116 This process lacks permission to make the requested change.
2118 Only privileged users or the file's owner can change the file's group.
2119 On most file systems, only privileged users can change the file owner;
2120 some file systems allow you to change the owner if you are currently the
2121 owner.  When you access a remote file system, the behavior you encounter
2122 is determined by the system that actually holds the file, not by the
2123 system your program is running on.
2125 @xref{Options for Files}, for information about the
2126 @code{_POSIX_CHOWN_RESTRICTED} macro.
2128 @item EROFS
2129 The file is on a read-only file system.
2130 @end table
2131 @end deftypefun
2133 @comment unistd.h
2134 @comment BSD
2135 @deftypefun int fchown (int @var{filedes}, int @var{owner}, int @var{group})
2136 This is like @code{chown}, except that it changes the owner of the open
2137 file with descriptor @var{filedes}.
2139 The return value from @code{fchown} is @code{0} on success and @code{-1}
2140 on failure.  The following @code{errno} error codes are defined for this
2141 function:
2143 @table @code
2144 @item EBADF
2145 The @var{filedes} argument is not a valid file descriptor.
2147 @item EINVAL
2148 The @var{filedes} argument corresponds to a pipe or socket, not an ordinary
2149 file.
2151 @item EPERM
2152 This process lacks permission to make the requested change.  For details
2153 see @code{chmod} above.
2155 @item EROFS
2156 The file resides on a read-only file system.
2157 @end table
2158 @end deftypefun
2160 @node Permission Bits
2161 @subsection The Mode Bits for Access Permission
2163 The @dfn{file mode}, stored in the @code{st_mode} field of the file
2164 attributes, contains two kinds of information: the file type code, and
2165 the access permission bits.  This section discusses only the access
2166 permission bits, which control who can read or write the file.
2167 @xref{Testing File Type}, for information about the file type code.
2169 All of the symbols listed in this section are defined in the header file
2170 @file{sys/stat.h}.
2171 @pindex sys/stat.h
2173 @cindex file permission bits
2174 These symbolic constants are defined for the file mode bits that control
2175 access permission for the file:
2177 @table @code
2178 @comment sys/stat.h
2179 @comment POSIX.1
2180 @item S_IRUSR
2181 @vindex S_IRUSR
2182 @comment sys/stat.h
2183 @comment BSD
2184 @itemx S_IREAD
2185 @vindex S_IREAD
2186 Read permission bit for the owner of the file.  On many systems this bit
2187 is 0400.  @code{S_IREAD} is an obsolete synonym provided for BSD
2188 compatibility.
2190 @comment sys/stat.h
2191 @comment POSIX.1
2192 @item S_IWUSR
2193 @vindex S_IWUSR
2194 @comment sys/stat.h
2195 @comment BSD
2196 @itemx S_IWRITE
2197 @vindex S_IWRITE
2198 Write permission bit for the owner of the file.  Usually 0200.
2199 @w{@code{S_IWRITE}} is an obsolete synonym provided for BSD compatibility.
2201 @comment sys/stat.h
2202 @comment POSIX.1
2203 @item S_IXUSR
2204 @vindex S_IXUSR
2205 @comment sys/stat.h
2206 @comment BSD
2207 @itemx S_IEXEC
2208 @vindex S_IEXEC
2209 Execute (for ordinary files) or search (for directories) permission bit
2210 for the owner of the file.  Usually 0100.  @code{S_IEXEC} is an obsolete
2211 synonym provided for BSD compatibility.
2213 @comment sys/stat.h
2214 @comment POSIX.1
2215 @item S_IRWXU
2216 @vindex S_IRWXU
2217 This is equivalent to @samp{(S_IRUSR | S_IWUSR | S_IXUSR)}.
2219 @comment sys/stat.h
2220 @comment POSIX.1
2221 @item S_IRGRP
2222 @vindex S_IRGRP
2223 Read permission bit for the group owner of the file.  Usually 040.
2225 @comment sys/stat.h
2226 @comment POSIX.1
2227 @item S_IWGRP
2228 @vindex S_IWGRP
2229 Write permission bit for the group owner of the file.  Usually 020.
2231 @comment sys/stat.h
2232 @comment POSIX.1
2233 @item S_IXGRP
2234 @vindex S_IXGRP
2235 Execute or search permission bit for the group owner of the file.
2236 Usually 010.
2238 @comment sys/stat.h
2239 @comment POSIX.1
2240 @item S_IRWXG
2241 @vindex S_IRWXG
2242 This is equivalent to @samp{(S_IRGRP | S_IWGRP | S_IXGRP)}.
2244 @comment sys/stat.h
2245 @comment POSIX.1
2246 @item S_IROTH
2247 @vindex S_IROTH
2248 Read permission bit for other users.  Usually 04.
2250 @comment sys/stat.h
2251 @comment POSIX.1
2252 @item S_IWOTH
2253 @vindex S_IWOTH
2254 Write permission bit for other users.  Usually 02.
2256 @comment sys/stat.h
2257 @comment POSIX.1
2258 @item S_IXOTH
2259 @vindex S_IXOTH
2260 Execute or search permission bit for other users.  Usually 01.
2262 @comment sys/stat.h
2263 @comment POSIX.1
2264 @item S_IRWXO
2265 @vindex S_IRWXO
2266 This is equivalent to @samp{(S_IROTH | S_IWOTH | S_IXOTH)}.
2268 @comment sys/stat.h
2269 @comment POSIX
2270 @item S_ISUID
2271 @vindex S_ISUID
2272 This is the set-user-ID on execute bit, usually 04000.
2273 @xref{How Change Persona}.
2275 @comment sys/stat.h
2276 @comment POSIX
2277 @item S_ISGID
2278 @vindex S_ISGID
2279 This is the set-group-ID on execute bit, usually 02000.
2280 @xref{How Change Persona}.
2282 @cindex sticky bit
2283 @comment sys/stat.h
2284 @comment BSD
2285 @item S_ISVTX
2286 @vindex S_ISVTX
2287 This is the @dfn{sticky} bit, usually 01000.
2289 For a directory it gives permission to delete a file in that directory
2290 only if you own that file.  Ordinarily, a user can either delete all the
2291 files in a directory or cannot delete any of them (based on whether the
2292 user has write permission for the directory).  The same restriction
2293 applies---you must have both write permission for the directory and own
2294 the file you want to delete.  The one exception is that the owner of the
2295 directory can delete any file in the directory, no matter who owns it
2296 (provided the owner has given himself write permission for the
2297 directory).  This is commonly used for the @file{/tmp} directory, where
2298 anyone may create files but not delete files created by other users.
2300 Originally the sticky bit on an executable file modified the swapping
2301 policies of the system.  Normally, when a program terminated, its pages
2302 in core were immediately freed and reused.  If the sticky bit was set on
2303 the executable file, the system kept the pages in core for a while as if
2304 the program were still running.  This was advantageous for a program
2305 likely to be run many times in succession.  This usage is obsolete in
2306 modern systems.  When a program terminates, its pages always remain in
2307 core as long as there is no shortage of memory in the system.  When the
2308 program is next run, its pages will still be in core if no shortage
2309 arose since the last run.
2311 On some modern systems where the sticky bit has no useful meaning for an
2312 executable file, you cannot set the bit at all for a non-directory.
2313 If you try, @code{chmod} fails with @code{EFTYPE};
2314 @pxref{Setting Permissions}.
2316 Some systems (particularly SunOS) have yet another use for the sticky
2317 bit.  If the sticky bit is set on a file that is @emph{not} executable,
2318 it means the opposite: never cache the pages of this file at all.  The
2319 main use of this is for the files on an NFS server machine which are
2320 used as the swap area of diskless client machines.  The idea is that the
2321 pages of the file will be cached in the client's memory, so it is a
2322 waste of the server's memory to cache them a second time.  With this
2323 usage the sticky bit also implies that the filesystem may fail to record
2324 the file's modification time onto disk reliably (the idea being that
2325 no-one cares for a swap file).
2327 This bit is only available on BSD systems (and those derived from
2328 them).  Therefore one has to use the @code{_BSD_SOURCE} feature select
2329 macro to get the definition (@pxref{Feature Test Macros}).
2330 @end table
2332 The actual bit values of the symbols are listed in the table above
2333 so you can decode file mode values when debugging your programs.
2334 These bit values are correct for most systems, but they are not
2335 guaranteed.
2337 @strong{Warning:} Writing explicit numbers for file permissions is bad
2338 practice.  Not only is it not portable, it also requires everyone who
2339 reads your program to remember what the bits mean.  To make your program
2340 clean use the symbolic names.
2342 @node Access Permission
2343 @subsection How Your Access to a File is Decided
2344 @cindex permission to access a file
2345 @cindex access permission for a file
2346 @cindex file access permission
2348 Recall that the operating system normally decides access permission for
2349 a file based on the effective user and group IDs of the process and its
2350 supplementary group IDs, together with the file's owner, group and
2351 permission bits.  These concepts are discussed in detail in @ref{Process
2352 Persona}.
2354 If the effective user ID of the process matches the owner user ID of the
2355 file, then permissions for read, write, and execute/search are
2356 controlled by the corresponding ``user'' (or ``owner'') bits.  Likewise,
2357 if any of the effective group ID or supplementary group IDs of the
2358 process matches the group owner ID of the file, then permissions are
2359 controlled by the ``group'' bits.  Otherwise, permissions are controlled
2360 by the ``other'' bits.
2362 Privileged users, like @samp{root}, can access any file regardless of
2363 its permission bits.  As a special case, for a file to be executable
2364 even by a privileged user, at least one of its execute bits must be set.
2366 @node Setting Permissions
2367 @subsection Assigning File Permissions
2369 @cindex file creation mask
2370 @cindex umask
2371 The primitive functions for creating files (for example, @code{open} or
2372 @code{mkdir}) take a @var{mode} argument, which specifies the file
2373 permissions to give the newly created file.  This mode is modified by
2374 the process's @dfn{file creation mask}, or @dfn{umask}, before it is
2375 used.
2377 The bits that are set in the file creation mask identify permissions
2378 that are always to be disabled for newly created files.  For example, if
2379 you set all the ``other'' access bits in the mask, then newly created
2380 files are not accessible at all to processes in the ``other'' category,
2381 even if the @var{mode} argument passed to the create function would
2382 permit such access.  In other words, the file creation mask is the
2383 complement of the ordinary access permissions you want to grant.
2385 Programs that create files typically specify a @var{mode} argument that
2386 includes all the permissions that make sense for the particular file.
2387 For an ordinary file, this is typically read and write permission for
2388 all classes of users.  These permissions are then restricted as
2389 specified by the individual user's own file creation mask.
2391 @findex chmod
2392 To change the permission of an existing file given its name, call
2393 @code{chmod}.  This function uses the specified permission bits and
2394 ignores the file creation mask.
2396 @pindex umask
2397 In normal use, the file creation mask is initialized by the user's login
2398 shell (using the @code{umask} shell command), and inherited by all
2399 subprocesses.  Application programs normally don't need to worry about
2400 the file creation mask.  It will automatically do what it is supposed to
2403 When your program needs to create a file and bypass the umask for its
2404 access permissions, the easiest way to do this is to use @code{fchmod}
2405 after opening the file, rather than changing the umask.  In fact,
2406 changing the umask is usually done only by shells.  They use the
2407 @code{umask} function.
2409 The functions in this section are declared in @file{sys/stat.h}.
2410 @pindex sys/stat.h
2412 @comment sys/stat.h
2413 @comment POSIX.1
2414 @deftypefun mode_t umask (mode_t @var{mask})
2415 The @code{umask} function sets the file creation mask of the current
2416 process to @var{mask}, and returns the previous value of the file
2417 creation mask.
2419 Here is an example showing how to read the mask with @code{umask}
2420 without changing it permanently:
2422 @smallexample
2423 mode_t
2424 read_umask (void)
2426   mode_t mask = umask (0);
2427   umask (mask);
2428   return mask;
2430 @end smallexample
2432 @noindent
2433 However, it is better to use @code{getumask} if you just want to read
2434 the mask value, because it is reentrant (at least if you use the GNU
2435 operating system).
2436 @end deftypefun
2438 @comment sys/stat.h
2439 @comment GNU
2440 @deftypefun mode_t getumask (void)
2441 Return the current value of the file creation mask for the current
2442 process.  This function is a GNU extension.
2443 @end deftypefun
2445 @comment sys/stat.h
2446 @comment POSIX.1
2447 @deftypefun int chmod (const char *@var{filename}, mode_t @var{mode})
2448 The @code{chmod} function sets the access permission bits for the file
2449 named by @var{filename} to @var{mode}.
2451 If @var{filename} is a symbolic link, @code{chmod} changes the
2452 permissions of the file pointed to by the link, not those of the link
2453 itself.
2455 This function returns @code{0} if successful and @code{-1} if not.  In
2456 addition to the usual file name errors (@pxref{File Name
2457 Errors}), the following @code{errno} error conditions are defined for
2458 this function:
2460 @table @code
2461 @item ENOENT
2462 The named file doesn't exist.
2464 @item EPERM
2465 This process does not have permission to change the access permissions
2466 of this file.  Only the file's owner (as judged by the effective user ID
2467 of the process) or a privileged user can change them.
2469 @item EROFS
2470 The file resides on a read-only file system.
2472 @item EFTYPE
2473 @var{mode} has the @code{S_ISVTX} bit (the ``sticky bit'') set,
2474 and the named file is not a directory.  Some systems do not allow setting the
2475 sticky bit on non-directory files, and some do (and only some of those
2476 assign a useful meaning to the bit for non-directory files).
2478 You only get @code{EFTYPE} on systems where the sticky bit has no useful
2479 meaning for non-directory files, so it is always safe to just clear the
2480 bit in @var{mode} and call @code{chmod} again.  @xref{Permission Bits},
2481 for full details on the sticky bit.
2482 @end table
2483 @end deftypefun
2485 @comment sys/stat.h
2486 @comment BSD
2487 @deftypefun int fchmod (int @var{filedes}, int @var{mode})
2488 This is like @code{chmod}, except that it changes the permissions of the
2489 currently open file given by @var{filedes}.
2491 The return value from @code{fchmod} is @code{0} on success and @code{-1}
2492 on failure.  The following @code{errno} error codes are defined for this
2493 function:
2495 @table @code
2496 @item EBADF
2497 The @var{filedes} argument is not a valid file descriptor.
2499 @item EINVAL
2500 The @var{filedes} argument corresponds to a pipe or socket, or something
2501 else that doesn't really have access permissions.
2503 @item EPERM
2504 This process does not have permission to change the access permissions
2505 of this file.  Only the file's owner (as judged by the effective user ID
2506 of the process) or a privileged user can change them.
2508 @item EROFS
2509 The file resides on a read-only file system.
2510 @end table
2511 @end deftypefun
2513 @node Testing File Access
2514 @subsection Testing Permission to Access a File
2515 @cindex testing access permission
2516 @cindex access, testing for
2517 @cindex setuid programs and file access
2519 In some situations it is desirable to allow programs to access files or
2520 devices even if this is not possible with the permissions granted to the
2521 user.  One possible solution is to set the setuid-bit of the program
2522 file.  If such a program is started the @emph{effective} user ID of the
2523 process is changed to that of the owner of the program file.  So to
2524 allow write access to files like @file{/etc/passwd}, which normally can
2525 be written only by the super-user, the modifying program will have to be
2526 owned by @code{root} and the setuid-bit must be set.
2528 But beside the files the program is intended to change the user should
2529 not be allowed to access any file to which s/he would not have access
2530 anyway.  The program therefore must explicitly check whether @emph{the
2531 user} would have the necessary access to a file, before it reads or
2532 writes the file.
2534 To do this, use the function @code{access}, which checks for access
2535 permission based on the process's @emph{real} user ID rather than the
2536 effective user ID.  (The setuid feature does not alter the real user ID,
2537 so it reflects the user who actually ran the program.)
2539 There is another way you could check this access, which is easy to
2540 describe, but very hard to use.  This is to examine the file mode bits
2541 and mimic the system's own access computation.  This method is
2542 undesirable because many systems have additional access control
2543 features; your program cannot portably mimic them, and you would not
2544 want to try to keep track of the diverse features that different systems
2545 have.  Using @code{access} is simple and automatically does whatever is
2546 appropriate for the system you are using.
2548 @code{access} is @emph{only} only appropriate to use in setuid programs.
2549 A non-setuid program will always use the effective ID rather than the
2550 real ID.
2552 @pindex unistd.h
2553 The symbols in this section are declared in @file{unistd.h}.
2555 @comment unistd.h
2556 @comment POSIX.1
2557 @deftypefun int access (const char *@var{filename}, int @var{how})
2558 The @code{access} function checks to see whether the file named by
2559 @var{filename} can be accessed in the way specified by the @var{how}
2560 argument.  The @var{how} argument either can be the bitwise OR of the
2561 flags @code{R_OK}, @code{W_OK}, @code{X_OK}, or the existence test
2562 @code{F_OK}.
2564 This function uses the @emph{real} user and group IDs of the calling
2565 process, rather than the @emph{effective} IDs, to check for access
2566 permission.  As a result, if you use the function from a @code{setuid}
2567 or @code{setgid} program (@pxref{How Change Persona}), it gives
2568 information relative to the user who actually ran the program.
2570 The return value is @code{0} if the access is permitted, and @code{-1}
2571 otherwise.  (In other words, treated as a predicate function,
2572 @code{access} returns true if the requested access is @emph{denied}.)
2574 In addition to the usual file name errors (@pxref{File Name
2575 Errors}), the following @code{errno} error conditions are defined for
2576 this function:
2578 @table @code
2579 @item EACCES
2580 The access specified by @var{how} is denied.
2582 @item ENOENT
2583 The file doesn't exist.
2585 @item EROFS
2586 Write permission was requested for a file on a read-only file system.
2587 @end table
2588 @end deftypefun
2590 These macros are defined in the header file @file{unistd.h} for use
2591 as the @var{how} argument to the @code{access} function.  The values
2592 are integer constants.
2593 @pindex unistd.h
2595 @comment unistd.h
2596 @comment POSIX.1
2597 @deftypevr Macro int R_OK
2598 Flag meaning test for read permission.
2599 @end deftypevr
2601 @comment unistd.h
2602 @comment POSIX.1
2603 @deftypevr Macro int W_OK
2604 Flag meaning test for write permission.
2605 @end deftypevr
2607 @comment unistd.h
2608 @comment POSIX.1
2609 @deftypevr Macro int X_OK
2610 Flag meaning test for execute/search permission.
2611 @end deftypevr
2613 @comment unistd.h
2614 @comment POSIX.1
2615 @deftypevr Macro int F_OK
2616 Flag meaning test for existence of the file.
2617 @end deftypevr
2619 @node File Times
2620 @subsection File Times
2622 @cindex file access time
2623 @cindex file modification time
2624 @cindex file attribute modification time
2625 Each file has three time stamps associated with it:  its access time,
2626 its modification time, and its attribute modification time.  These
2627 correspond to the @code{st_atime}, @code{st_mtime}, and @code{st_ctime}
2628 members of the @code{stat} structure; see @ref{File Attributes}.
2630 All of these times are represented in calendar time format, as
2631 @code{time_t} objects.  This data type is defined in @file{time.h}.
2632 For more information about representation and manipulation of time
2633 values, see @ref{Calendar Time}.
2634 @pindex time.h
2636 Reading from a file updates its access time attribute, and writing
2637 updates its modification time.  When a file is created, all three
2638 time stamps for that file are set to the current time.  In addition, the
2639 attribute change time and modification time fields of the directory that
2640 contains the new entry are updated.
2642 Adding a new name for a file with the @code{link} function updates the
2643 attribute change time field of the file being linked, and both the
2644 attribute change time and modification time fields of the directory
2645 containing the new name.  These same fields are affected if a file name
2646 is deleted with @code{unlink}, @code{remove} or @code{rmdir}.  Renaming
2647 a file with @code{rename} affects only the attribute change time and
2648 modification time fields of the two parent directories involved, and not
2649 the times for the file being renamed.
2651 Changing the attributes of a file (for example, with @code{chmod})
2652 updates its attribute change time field.
2654 You can also change some of the time stamps of a file explicitly using
2655 the @code{utime} function---all except the attribute change time.  You
2656 need to include the header file @file{utime.h} to use this facility.
2657 @pindex utime.h
2659 @comment time.h
2660 @comment POSIX.1
2661 @deftp {Data Type} {struct utimbuf}
2662 The @code{utimbuf} structure is used with the @code{utime} function to
2663 specify new access and modification times for a file.  It contains the
2664 following members:
2666 @table @code
2667 @item time_t actime
2668 This is the access time for the file.
2670 @item time_t modtime
2671 This is the modification time for the file.
2672 @end table
2673 @end deftp
2675 @comment time.h
2676 @comment POSIX.1
2677 @deftypefun int utime (const char *@var{filename}, const struct utimbuf *@var{times})
2678 This function is used to modify the file times associated with the file
2679 named @var{filename}.
2681 If @var{times} is a null pointer, then the access and modification times
2682 of the file are set to the current time.  Otherwise, they are set to the
2683 values from the @code{actime} and @code{modtime} members (respectively)
2684 of the @code{utimbuf} structure pointed to by @var{times}.
2686 The attribute modification time for the file is set to the current time
2687 in either case (since changing the time stamps is itself a modification
2688 of the file attributes).
2690 The @code{utime} function returns @code{0} if successful and @code{-1}
2691 on failure.  In addition to the usual file name errors
2692 (@pxref{File Name Errors}), the following @code{errno} error conditions
2693 are defined for this function:
2695 @table @code
2696 @item EACCES
2697 There is a permission problem in the case where a null pointer was
2698 passed as the @var{times} argument.  In order to update the time stamp on
2699 the file, you must either be the owner of the file, have write
2700 permission for the file, or be a privileged user.
2702 @item ENOENT
2703 The file doesn't exist.
2705 @item EPERM
2706 If the @var{times} argument is not a null pointer, you must either be
2707 the owner of the file or be a privileged user.
2709 @item EROFS
2710 The file lives on a read-only file system.
2711 @end table
2712 @end deftypefun
2714 Each of the three time stamps has a corresponding microsecond part,
2715 which extends its resolution.  These fields are called
2716 @code{st_atime_usec}, @code{st_mtime_usec}, and @code{st_ctime_usec};
2717 each has a value between 0 and 999,999, which indicates the time in
2718 microseconds.  They correspond to the @code{tv_usec} field of a
2719 @code{timeval} structure; see @ref{High-Resolution Calendar}.
2721 The @code{utimes} function is like @code{utime}, but also lets you specify
2722 the fractional part of the file times.  The prototype for this function is
2723 in the header file @file{sys/time.h}.
2724 @pindex sys/time.h
2726 @comment sys/time.h
2727 @comment BSD
2728 @deftypefun int utimes (const char *@var{filename}, struct timeval @var{tvp}@t{[2]})
2729 This function sets the file access and modification times of the file
2730 @var{filename}.  The new file access time is specified by
2731 @code{@var{tvp}[0]}, and the new modification time by
2732 @code{@var{tvp}[1]}.  Similar to @code{utime}, if @var{tvp} is a null
2733 pointer then the access and modification times of the file are set to
2734 the current time.  This function comes from BSD.
2736 The return values and error conditions are the same as for the @code{utime}
2737 function.
2738 @end deftypefun
2740 @comment sys/time.h
2741 @comment BSD
2742 @deftypefun int lutimes (const char *@var{filename}, struct timeval @var{tvp}@t{[2]})
2743 This function is like @code{utimes}, except that it does not follow
2744 symbolic links.  If @var{filename} is the name of a symbolic link,
2745 @code{lutimes} sets the file access and modification times of the
2746 symbolic link special file itself (as seen by @code{lstat};
2747 @pxref{Symbolic Links}) while @code{utimes} sets the file access and
2748 modification times of the file the symbolic link refers to.  This
2749 function comes from FreeBSD, and is not available on all platforms (if
2750 not available, it will fail with @code{ENOSYS}).
2752 The return values and error conditions are the same as for the @code{utime}
2753 function.
2754 @end deftypefun
2756 @comment sys/time.h
2757 @comment BSD
2758 @deftypefun int futimes (int *@var{fd}, struct timeval @var{tvp}@t{[2]})
2759 This function is like @code{utimes}, except that it takes an open file
2760 descriptor as an argument instead of a file name.  @xref{Low-Level
2761 I/O}.  This function comes from FreeBSD, and is not available on all
2762 platforms (if not available, it will fail with @code{ENOSYS}).
2764 Like @code{utimes}, @code{futimes} returns @code{0} on success and @code{-1}
2765 on failure.  The following @code{errno} error conditions are defined for
2766 @code{futimes}:
2768 @table @code
2769 @item EACCES
2770 There is a permission problem in the case where a null pointer was
2771 passed as the @var{times} argument.  In order to update the time stamp on
2772 the file, you must either be the owner of the file, have write
2773 permission for the file, or be a privileged user.
2775 @item EBADF
2776 The @var{filedes} argument is not a valid file descriptor.
2778 @item EPERM
2779 If the @var{times} argument is not a null pointer, you must either be
2780 the owner of the file or be a privileged user.
2782 @item EROFS
2783 The file lives on a read-only file system.
2784 @end table
2785 @end deftypefun
2787 @node File Size
2788 @subsection File Size
2790 Normally file sizes are maintained automatically.  A file begins with a
2791 size of @math{0} and is automatically extended when data is written past
2792 its end.  It is also possible to empty a file completely by an
2793 @code{open} or @code{fopen} call.
2795 However, sometimes it is necessary to @emph{reduce} the size of a file.
2796 This can be done with the @code{truncate} and @code{ftruncate} functions.
2797 They were introduced in BSD Unix.  @code{ftruncate} was later added to
2798 POSIX.1.
2800 Some systems allow you to extend a file (creating holes) with these
2801 functions.  This is useful when using memory-mapped I/O
2802 (@pxref{Memory-mapped I/O}), where files are not automatically extended.
2803 However, it is not portable but must be implemented if @code{mmap}
2804 allows mapping of files (i.e., @code{_POSIX_MAPPED_FILES} is defined).
2806 Using these functions on anything other than a regular file gives
2807 @emph{undefined} results.  On many systems, such a call will appear to
2808 succeed, without actually accomplishing anything.
2810 @comment unistd.h
2811 @comment X/Open
2812 @deftypefun int truncate (const char *@var{filename}, off_t @var{length})
2814 The @code{truncate} function changes the size of @var{filename} to
2815 @var{length}.  If @var{length} is shorter than the previous length, data
2816 at the end will be lost.  The file must be writable by the user to
2817 perform this operation.
2819 If @var{length} is longer, holes will be added to the end.  However, some
2820 systems do not support this feature and will leave the file unchanged.
2822 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
2823 @code{truncate} function is in fact @code{truncate64} and the type
2824 @code{off_t} has 64 bits which makes it possible to handle files up to
2825 @math{2^63} bytes in length.
2827 The return value is @math{0} for success, or @math{-1} for an error.  In
2828 addition to the usual file name errors, the following errors may occur:
2830 @table @code
2832 @item EACCES
2833 The file is a directory or not writable.
2835 @item EINVAL
2836 @var{length} is negative.
2838 @item EFBIG
2839 The operation would extend the file beyond the limits of the operating system.
2841 @item EIO
2842 A hardware I/O error occurred.
2844 @item EPERM
2845 The file is "append-only" or "immutable".
2847 @item EINTR
2848 The operation was interrupted by a signal.
2850 @end table
2852 @end deftypefun
2854 @comment unistd.h
2855 @comment Unix98
2856 @deftypefun int truncate64 (const char *@var{name}, off64_t @var{length})
2857 This function is similar to the @code{truncate} function.  The
2858 difference is that the @var{length} argument is 64 bits wide even on 32
2859 bits machines, which allows the handling of files with sizes up to
2860 @math{2^63} bytes.
2862 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
2863 32 bits machine this function is actually available under the name
2864 @code{truncate} and so transparently replaces the 32 bits interface.
2865 @end deftypefun
2867 @comment unistd.h
2868 @comment POSIX
2869 @deftypefun int ftruncate (int @var{fd}, off_t @var{length})
2871 This is like @code{truncate}, but it works on a file descriptor @var{fd}
2872 for an opened file instead of a file name to identify the object.  The
2873 file must be opened for writing to successfully carry out the operation.
2875 The POSIX standard leaves it implementation defined what happens if the
2876 specified new @var{length} of the file is bigger than the original size.
2877 The @code{ftruncate} function might simply leave the file alone and do
2878 nothing or it can increase the size to the desired size.  In this later
2879 case the extended area should be zero-filled.  So using @code{ftruncate}
2880 is no reliable way to increase the file size but if it is possible it is
2881 probably the fastest way.  The function also operates on POSIX shared
2882 memory segments if these are implemented by the system.
2884 @code{ftruncate} is especially useful in combination with @code{mmap}.
2885 Since the mapped region must have a fixed size one cannot enlarge the
2886 file by writing something beyond the last mapped page.  Instead one has
2887 to enlarge the file itself and then remap the file with the new size.
2888 The example below shows how this works.
2890 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
2891 @code{ftruncate} function is in fact @code{ftruncate64} and the type
2892 @code{off_t} has 64 bits which makes it possible to handle files up to
2893 @math{2^63} bytes in length.
2895 The return value is @math{0} for success, or @math{-1} for an error.  The
2896 following errors may occur:
2898 @table @code
2900 @item EBADF
2901 @var{fd} does not correspond to an open file.
2903 @item EACCES
2904 @var{fd} is a directory or not open for writing.
2906 @item EINVAL
2907 @var{length} is negative.
2909 @item EFBIG
2910 The operation would extend the file beyond the limits of the operating system.
2911 @c or the open() call -- with the not-yet-discussed feature of opening
2912 @c files with extra-large offsets.
2914 @item EIO
2915 A hardware I/O error occurred.
2917 @item EPERM
2918 The file is "append-only" or "immutable".
2920 @item EINTR
2921 The operation was interrupted by a signal.
2923 @c ENOENT is also possible on Linux --- however it only occurs if the file
2924 @c descriptor has a `file' structure but no `inode' structure.  I'm not
2925 @c sure how such an fd could be created.  Perhaps it's a bug.
2927 @end table
2929 @end deftypefun
2931 @comment unistd.h
2932 @comment Unix98
2933 @deftypefun int ftruncate64 (int @var{id}, off64_t @var{length})
2934 This function is similar to the @code{ftruncate} function.  The
2935 difference is that the @var{length} argument is 64 bits wide even on 32
2936 bits machines which allows the handling of files with sizes up to
2937 @math{2^63} bytes.
2939 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
2940 32 bits machine this function is actually available under the name
2941 @code{ftruncate} and so transparently replaces the 32 bits interface.
2942 @end deftypefun
2944 As announced here is a little example of how to use @code{ftruncate} in
2945 combination with @code{mmap}:
2947 @smallexample
2948 int fd;
2949 void *start;
2950 size_t len;
2953 add (off_t at, void *block, size_t size)
2955   if (at + size > len)
2956     @{
2957       /* Resize the file and remap.  */
2958       size_t ps = sysconf (_SC_PAGESIZE);
2959       size_t ns = (at + size + ps - 1) & ~(ps - 1);
2960       void *np;
2961       if (ftruncate (fd, ns) < 0)
2962         return -1;
2963       np = mmap (NULL, ns, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
2964       if (np == MAP_FAILED)
2965         return -1;
2966       start = np;
2967       len = ns;
2968     @}
2969   memcpy ((char *) start + at, block, size);
2970   return 0;
2972 @end smallexample
2974 The function @code{add} writes a block of memory at an arbitrary
2975 position in the file.  If the current size of the file is too small it
2976 is extended.  Note the it is extended by a round number of pages.  This
2977 is a requirement of @code{mmap}.  The program has to keep track of the
2978 real size, and when it has finished a final @code{ftruncate} call should
2979 set the real size of the file.
2981 @node Making Special Files
2982 @section Making Special Files
2983 @cindex creating special files
2984 @cindex special files
2986 The @code{mknod} function is the primitive for making special files,
2987 such as files that correspond to devices.  The GNU library includes
2988 this function for compatibility with BSD.
2990 The prototype for @code{mknod} is declared in @file{sys/stat.h}.
2991 @pindex sys/stat.h
2993 @comment sys/stat.h
2994 @comment BSD
2995 @deftypefun int mknod (const char *@var{filename}, int @var{mode}, int @var{dev})
2996 The @code{mknod} function makes a special file with name @var{filename}.
2997 The @var{mode} specifies the mode of the file, and may include the various
2998 special file bits, such as @code{S_IFCHR} (for a character special file)
2999 or @code{S_IFBLK} (for a block special file).  @xref{Testing File Type}.
3001 The @var{dev} argument specifies which device the special file refers to.
3002 Its exact interpretation depends on the kind of special file being created.
3004 The return value is @code{0} on success and @code{-1} on error.  In addition
3005 to the usual file name errors (@pxref{File Name Errors}), the
3006 following @code{errno} error conditions are defined for this function:
3008 @table @code
3009 @item EPERM
3010 The calling process is not privileged.  Only the superuser can create
3011 special files.
3013 @item ENOSPC
3014 The directory or file system that would contain the new file is full
3015 and cannot be extended.
3017 @item EROFS
3018 The directory containing the new file can't be modified because it's on
3019 a read-only file system.
3021 @item EEXIST
3022 There is already a file named @var{filename}.  If you want to replace
3023 this file, you must remove the old file explicitly first.
3024 @end table
3025 @end deftypefun
3027 @node Temporary Files
3028 @section Temporary Files
3030 If you need to use a temporary file in your program, you can use the
3031 @code{tmpfile} function to open it.  Or you can use the @code{tmpnam}
3032 (better: @code{tmpnam_r}) function to provide a name for a temporary
3033 file and then you can open it in the usual way with @code{fopen}.
3035 The @code{tempnam} function is like @code{tmpnam} but lets you choose
3036 what directory temporary files will go in, and something about what
3037 their file names will look like.  Important for multi-threaded programs
3038 is that @code{tempnam} is reentrant, while @code{tmpnam} is not since it
3039 returns a pointer to a static buffer.
3041 These facilities are declared in the header file @file{stdio.h}.
3042 @pindex stdio.h
3044 @comment stdio.h
3045 @comment ISO
3046 @deftypefun {FILE *} tmpfile (void)
3047 This function creates a temporary binary file for update mode, as if by
3048 calling @code{fopen} with mode @code{"wb+"}.  The file is deleted
3049 automatically when it is closed or when the program terminates.  (On
3050 some other @w{ISO C} systems the file may fail to be deleted if the program
3051 terminates abnormally).
3053 This function is reentrant.
3055 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
3056 32-bit system this function is in fact @code{tmpfile64}, i.e. the LFS
3057 interface transparently replaces the old interface.
3058 @end deftypefun
3060 @comment stdio.h
3061 @comment Unix98
3062 @deftypefun {FILE *} tmpfile64 (void)
3063 This function is similar to @code{tmpfile}, but the stream it returns a
3064 pointer to was opened using @code{tmpfile64}.  Therefore this stream can
3065 be used for files larger then @math{2^31} bytes on 32-bit machines.
3067 Please note that the return type is still @code{FILE *}.  There is no
3068 special @code{FILE} type for the LFS interface.
3070 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
3071 bits machine this function is available under the name @code{tmpfile}
3072 and so transparently replaces the old interface.
3073 @end deftypefun
3075 @comment stdio.h
3076 @comment ISO
3077 @deftypefun {char *} tmpnam (char *@var{result})
3078 This function constructs and returns a valid file name that does not
3079 refer to any existing file.  If the @var{result} argument is a null
3080 pointer, the return value is a pointer to an internal static string,
3081 which might be modified by subsequent calls and therefore makes this
3082 function non-reentrant.  Otherwise, the @var{result} argument should be
3083 a pointer to an array of at least @code{L_tmpnam} characters, and the
3084 result is written into that array.
3086 It is possible for @code{tmpnam} to fail if you call it too many times
3087 without removing previously-created files.  This is because the limited
3088 length of the temporary file names gives room for only a finite number
3089 of different names.  If @code{tmpnam} fails it returns a null pointer.
3091 @strong{Warning:} Between the time the pathname is constructed and the
3092 file is created another process might have created a file with the same
3093 name using @code{tmpnam}, leading to a possible security hole.  The
3094 implementation generates names which can hardly be predicted, but when
3095 opening the file you should use the @code{O_EXCL} flag.  Using
3096 @code{tmpfile} or @code{mkstemp} is a safe way to avoid this problem.
3097 @end deftypefun
3099 @comment stdio.h
3100 @comment GNU
3101 @deftypefun {char *} tmpnam_r (char *@var{result})
3102 This function is nearly identical to the @code{tmpnam} function, except
3103 that if @var{result} is a null pointer it returns a null pointer.
3105 This guarantees reentrancy because the non-reentrant situation of
3106 @code{tmpnam} cannot happen here.
3108 @strong{Warning}: This function has the same security problems as
3109 @code{tmpnam}.
3110 @end deftypefun
3112 @comment stdio.h
3113 @comment ISO
3114 @deftypevr Macro int L_tmpnam
3115 The value of this macro is an integer constant expression that
3116 represents the minimum size of a string large enough to hold a file name
3117 generated by the @code{tmpnam} function.
3118 @end deftypevr
3120 @comment stdio.h
3121 @comment ISO
3122 @deftypevr Macro int TMP_MAX
3123 The macro @code{TMP_MAX} is a lower bound for how many temporary names
3124 you can create with @code{tmpnam}.  You can rely on being able to call
3125 @code{tmpnam} at least this many times before it might fail saying you
3126 have made too many temporary file names.
3128 With the GNU library, you can create a very large number of temporary
3129 file names.  If you actually created the files, you would probably run
3130 out of disk space before you ran out of names.  Some other systems have
3131 a fixed, small limit on the number of temporary files.  The limit is
3132 never less than @code{25}.
3133 @end deftypevr
3135 @comment stdio.h
3136 @comment SVID
3137 @deftypefun {char *} tempnam (const char *@var{dir}, const char *@var{prefix})
3138 This function generates a unique temporary file name.  If @var{prefix}
3139 is not a null pointer, up to five characters of this string are used as
3140 a prefix for the file name.  The return value is a string newly
3141 allocated with @code{malloc}, so you should release its storage with
3142 @code{free} when it is no longer needed.
3144 Because the string is dynamically allocated this function is reentrant.
3146 The directory prefix for the temporary file name is determined by
3147 testing each of the following in sequence.  The directory must exist and
3148 be writable.
3150 @itemize @bullet
3151 @item
3152 The environment variable @code{TMPDIR}, if it is defined.  For security
3153 reasons this only happens if the program is not SUID or SGID enabled.
3155 @item
3156 The @var{dir} argument, if it is not a null pointer.
3158 @item
3159 The value of the @code{P_tmpdir} macro.
3161 @item
3162 The directory @file{/tmp}.
3163 @end itemize
3165 This function is defined for SVID compatibility.
3167 @strong{Warning:} Between the time the pathname is constructed and the
3168 file is created another process might have created a file with the same
3169 name using @code{tempnam}, leading to a possible security hole.  The
3170 implementation generates names which can hardly be predicted, but when
3171 opening the file you should use the @code{O_EXCL} flag.  Using
3172 @code{tmpfile} or @code{mkstemp} is a safe way to avoid this problem.
3173 @end deftypefun
3174 @cindex TMPDIR environment variable
3176 @comment stdio.h
3177 @comment SVID
3178 @c !!! are we putting SVID/GNU/POSIX.1/BSD in here or not??
3179 @deftypevr {SVID Macro} {char *} P_tmpdir
3180 This macro is the name of the default directory for temporary files.
3181 @end deftypevr
3183 Older Unix systems did not have the functions just described.  Instead
3184 they used @code{mktemp} and @code{mkstemp}.  Both of these functions
3185 work by modifying a file name template string you pass.  The last six
3186 characters of this string must be @samp{XXXXXX}.  These six @samp{X}s
3187 are replaced with six characters which make the whole string a unique
3188 file name.  Usually the template string is something like
3189 @samp{/tmp/@var{prefix}XXXXXX}, and each program uses a unique @var{prefix}.
3191 @strong{Note:} Because @code{mktemp} and @code{mkstemp} modify the
3192 template string, you @emph{must not} pass string constants to them.
3193 String constants are normally in read-only storage, so your program
3194 would crash when @code{mktemp} or @code{mkstemp} tried to modify the
3195 string.  These functions are declared in the header file @file{stdlib.h}.
3196 @pindex stdlib.h
3198 @comment stdlib.h
3199 @comment Unix
3200 @deftypefun {char *} mktemp (char *@var{template})
3201 The @code{mktemp} function generates a unique file name by modifying
3202 @var{template} as described above.  If successful, it returns
3203 @var{template} as modified.  If @code{mktemp} cannot find a unique file
3204 name, it makes @var{template} an empty string and returns that.  If
3205 @var{template} does not end with @samp{XXXXXX}, @code{mktemp} returns a
3206 null pointer.
3208 @strong{Warning:} Between the time the pathname is constructed and the
3209 file is created another process might have created a file with the same
3210 name using @code{mktemp}, leading to a possible security hole.  The
3211 implementation generates names which can hardly be predicted, but when
3212 opening the file you should use the @code{O_EXCL} flag.  Using
3213 @code{mkstemp} is a safe way to avoid this problem.
3214 @end deftypefun
3216 @comment stdlib.h
3217 @comment BSD
3218 @deftypefun int mkstemp (char *@var{template})
3219 The @code{mkstemp} function generates a unique file name just as
3220 @code{mktemp} does, but it also opens the file for you with @code{open}
3221 (@pxref{Opening and Closing Files}).  If successful, it modifies
3222 @var{template} in place and returns a file descriptor for that file open
3223 for reading and writing.  If @code{mkstemp} cannot create a
3224 uniquely-named file, it returns @code{-1}.  If @var{template} does not
3225 end with @samp{XXXXXX}, @code{mkstemp} returns @code{-1} and does not
3226 modify @var{template}.
3228 The file is opened using mode @code{0600}.  If the file is meant to be
3229 used by other users this mode must be changed explicitly.
3230 @end deftypefun
3232 Unlike @code{mktemp}, @code{mkstemp} is actually guaranteed to create a
3233 unique file that cannot possibly clash with any other program trying to
3234 create a temporary file.  This is because it works by calling
3235 @code{open} with the @code{O_EXCL} flag, which says you want to create a
3236 new file and get an error if the file already exists.
3238 @comment stdlib.h
3239 @comment BSD
3240 @deftypefun {char *} mkdtemp (char *@var{template})
3241 The @code{mkdtemp} function creates a directory with a unique name.  If
3242 it succeeds, it overwrites @var{template} with the name of the
3243 directory, and returns @var{template}.  As with @code{mktemp} and
3244 @code{mkstemp}, @var{template} should be a string ending with
3245 @samp{XXXXXX}.
3247 If @code{mkdtemp} cannot create an uniquely named directory, it returns
3248 @code{NULL} and sets @var{errno} appropriately.  If @var{template} does
3249 not end with @samp{XXXXXX}, @code{mkdtemp} returns @code{NULL} and does
3250 not modify @var{template}.  @var{errno} will be set to @code{EINVAL} in
3251 this case.
3253 The directory is created using mode @code{0700}.
3254 @end deftypefun
3256 The directory created by @code{mkdtemp} cannot clash with temporary
3257 files or directories created by other users.  This is because directory
3258 creation always works like @code{open} with @code{O_EXCL}.
3259 @xref{Creating Directories}.
3261 The @code{mkdtemp} function comes from OpenBSD.