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