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