]> git.ipfire.org Git - thirdparty/glibc.git/blob - manual/filesys.texi
Update.
[thirdparty/glibc.git] / manual / filesys.texi
1 @node File System Interface, Pipes and FIFOs, Low-Level I/O, Top
2 @chapter File System Interface
3
4 This chapter describes the GNU C library's functions for manipulating
5 files. Unlike the input and output functions described in
6 @ref{I/O on Streams} and @ref{Low-Level I/O}, these
7 functions are concerned with operating on the files themselves, rather
8 than on their contents.
9
10 Among the facilities described in this chapter are functions for
11 examining or modifying directories, functions for renaming and deleting
12 files, and functions for examining and setting file attributes such as
13 access permissions and modification times.
14
15 @menu
16 * Working Directory:: This is used to resolve relative
17 file names.
18 * Accessing Directories:: Finding out what files a directory
19 contains.
20 * Hard Links:: Adding alternate names to a file.
21 * Symbolic Links:: A file that ``points to'' a file name.
22 * Deleting Files:: How to delete a file, and what that means.
23 * Renaming Files:: Changing a file's name.
24 * Creating Directories:: A system call just for creating a directory.
25 * File Attributes:: Attributes of individual files.
26 * Making Special Files:: How to create special files.
27 * Temporary Files:: Naming and creating temporary files.
28 @end menu
29
30 @node Working Directory
31 @section Working Directory
32
33 @cindex current working directory
34 @cindex working directory
35 @cindex change working directory
36 Each process has associated with it a directory, called its @dfn{current
37 working directory} or simply @dfn{working directory}, that is used in
38 the resolution of relative file names (@pxref{File Name Resolution}).
39
40 When you log in and begin a new session, your working directory is
41 initially set to the home directory associated with your login account
42 in the system user database. You can find any user's home directory
43 using the @code{getpwuid} or @code{getpwnam} functions; see @ref{User
44 Database}.
45
46 Users can change the working directory using shell commands like
47 @code{cd}. The functions described in this section are the primitives
48 used by those commands and by other programs for examining and changing
49 the working directory.
50 @pindex cd
51
52 Prototypes for these functions are declared in the header file
53 @file{unistd.h}.
54 @pindex unistd.h
55
56 @comment unistd.h
57 @comment POSIX.1
58 @deftypefun {char *} getcwd (char *@var{buffer}, size_t @var{size})
59 The @code{getcwd} function returns an absolute file name representing
60 the current working directory, storing it in the character array
61 @var{buffer} that you provide. The @var{size} argument is how you tell
62 the system the allocation size of @var{buffer}.
63
64 The GNU library version of this function also permits you to specify a
65 null pointer for the @var{buffer} argument. Then @code{getcwd}
66 allocates a buffer automatically, as with @code{malloc}
67 (@pxref{Unconstrained Allocation}). If the @var{size} is greater than
68 zero, then the buffer is that large; otherwise, the buffer is as large
69 as necessary to hold the result.
70
71 The return value is @var{buffer} on success and a null pointer on failure.
72 The following @code{errno} error conditions are defined for this function:
73
74 @table @code
75 @item EINVAL
76 The @var{size} argument is zero and @var{buffer} is not a null pointer.
77
78 @item ERANGE
79 The @var{size} argument is less than the length of the working directory
80 name. You need to allocate a bigger array and try again.
81
82 @item EACCES
83 Permission to read or search a component of the file name was denied.
84 @end table
85 @end deftypefun
86
87 Here is an example showing how you could implement the behavior of GNU's
88 @w{@code{getcwd (NULL, 0)}} using only the standard behavior of
89 @code{getcwd}:
90
91 @smallexample
92 char *
93 gnu_getcwd ()
94 @{
95 int size = 100;
96 char *buffer = (char *) xmalloc (size);
97
98 while (1)
99 @{
100 char *value = getcwd (buffer, size);
101 if (value != 0)
102 return buffer;
103 size *= 2;
104 free (buffer);
105 buffer = (char *) xmalloc (size);
106 @}
107 @}
108 @end smallexample
109
110 @noindent
111 @xref{Malloc Examples}, for information about @code{xmalloc}, which is
112 not a library function but is a customary name used in most GNU
113 software.
114
115 @comment unistd.h
116 @comment BSD
117 @deftypefun {char *} getwd (char *@var{buffer})
118 This is similar to @code{getcwd}, but has no way to specify the size of
119 the buffer. The GNU library provides @code{getwd} only
120 for backwards compatibility with BSD.
121
122 The @var{buffer} argument should be a pointer to an array at least
123 @code{PATH_MAX} bytes long (@pxref{Limits for Files}). In the GNU
124 system there is no limit to the size of a file name, so this is not
125 necessarily enough space to contain the directory name. That is why
126 this function is deprecated.
127 @end deftypefun
128
129 @comment unistd.h
130 @comment POSIX.1
131 @deftypefun int chdir (const char *@var{filename})
132 This function is used to set the process's working directory to
133 @var{filename}.
134
135 The normal, successful return value from @code{chdir} is @code{0}. A
136 value of @code{-1} is returned to indicate an error. The @code{errno}
137 error conditions defined for this function are the usual file name
138 syntax errors (@pxref{File Name Errors}), plus @code{ENOTDIR} if the
139 file @var{filename} is not a directory.
140 @end deftypefun
141
142
143 @node Accessing Directories
144 @section Accessing Directories
145 @cindex accessing directories
146 @cindex reading from a directory
147 @cindex directories, accessing
148
149 The facilities described in this section let you read the contents of a
150 directory file. This is useful if you want your program to list all the
151 files in a directory, perhaps as part of a menu.
152
153 @cindex directory stream
154 The @code{opendir} function opens a @dfn{directory stream} whose
155 elements are directory entries. You use the @code{readdir} function on
156 the directory stream to retrieve these entries, represented as
157 @w{@code{struct dirent}} objects. The name of the file for each entry is
158 stored in the @code{d_name} member of this structure. There are obvious
159 parallels here to the stream facilities for ordinary files, described in
160 @ref{I/O on Streams}.
161
162 @menu
163 * Directory Entries:: Format of one directory entry.
164 * Opening a Directory:: How to open a directory stream.
165 * Reading/Closing Directory:: How to read directory entries from the stream.
166 * Simple Directory Lister:: A very simple directory listing program.
167 * Random Access Directory:: Rereading part of the directory
168 already read with the same stream.
169 * Scanning Directory Content:: Get entries for user selected subset of
170 contents in given directory.
171 * Simple Directory Lister Mark II:: Revised version of the program.
172 @end menu
173
174 @node Directory Entries
175 @subsection Format of a Directory Entry
176
177 @pindex dirent.h
178 This section describes what you find in a single directory entry, as you
179 might obtain it from a directory stream. All the symbols are declared
180 in the header file @file{dirent.h}.
181
182 @comment dirent.h
183 @comment POSIX.1
184 @deftp {Data Type} {struct dirent}
185 This is a structure type used to return information about directory
186 entries. It contains the following fields:
187
188 @table @code
189 @item char d_name[]
190 This is the null-terminated file name component. This is the only
191 field you can count on in all POSIX systems.
192
193 @item ino_t d_fileno
194 This is the file serial number. For BSD compatibility, you can also
195 refer to this member as @code{d_ino}. In the GNU system and most POSIX
196 systems, for most files this the same as the @code{st_ino} member that
197 @code{stat} will return for the file. @xref{File Attributes}.
198
199 @item unsigned char d_namlen
200 This is the length of the file name, not including the terminating null
201 character. Its type is @code{unsigned char} because that is the integer
202 type of the appropriate size
203
204 @item unsigned char d_type
205 This is the type of the file, possibly unknown. The following constants
206 are defined for its value:
207
208 @table @code
209 @item DT_UNKNOWN
210 The type is unknown. On some systems this is the only value returned.
211
212 @item DT_REG
213 A regular file.
214
215 @item DT_DIR
216 A directory.
217
218 @item DT_FIFO
219 A named pipe, or FIFO. @xref{FIFO Special Files}.
220
221 @item DT_SOCK
222 A local-domain socket. @c !!! @xref{Local Domain}.
223
224 @item DT_CHR
225 A character device.
226
227 @item DT_BLK
228 A block device.
229 @end table
230
231 This member is a BSD extension. Each value except DT_UNKNOWN
232 corresponds to the file type bits in the @code{st_mode} member of
233 @code{struct statbuf}. These two macros convert between @code{d_type}
234 values and @code{st_mode} values:
235
236 @deftypefun int IFTODT (mode_t @var{mode})
237 This returns the @code{d_type} value corresponding to @var{mode}.
238 @end deftypefun
239
240 @deftypefun mode_t DTTOIF (int @var{dirtype})
241 This returns the @code{st_mode} value corresponding to @var{dirtype}.
242 @end deftypefun
243 @end table
244
245 This structure may contain additional members in the future.
246
247 When a file has multiple names, each name has its own directory entry.
248 The only way you can tell that the directory entries belong to a
249 single file is that they have the same value for the @code{d_fileno}
250 field.
251
252 File attributes such as size, modification times, and the like are part
253 of the file itself, not any particular directory entry. @xref{File
254 Attributes}.
255 @end deftp
256
257 @node Opening a Directory
258 @subsection Opening a Directory Stream
259
260 @pindex dirent.h
261 This section describes how to open a directory stream. All the symbols
262 are declared in the header file @file{dirent.h}.
263
264 @comment dirent.h
265 @comment POSIX.1
266 @deftp {Data Type} DIR
267 The @code{DIR} data type represents a directory stream.
268 @end deftp
269
270 You shouldn't ever allocate objects of the @code{struct dirent} or
271 @code{DIR} data types, since the directory access functions do that for
272 you. Instead, you refer to these objects using the pointers returned by
273 the following functions.
274
275 @comment dirent.h
276 @comment POSIX.1
277 @deftypefun {DIR *} opendir (const char *@var{dirname})
278 The @code{opendir} function opens and returns a directory stream for
279 reading the directory whose file name is @var{dirname}. The stream has
280 type @code{DIR *}.
281
282 If unsuccessful, @code{opendir} returns a null pointer. In addition to
283 the usual file name errors (@pxref{File Name Errors}), the
284 following @code{errno} error conditions are defined for this function:
285
286 @table @code
287 @item EACCES
288 Read permission is denied for the directory named by @code{dirname}.
289
290 @item EMFILE
291 The process has too many files open.
292
293 @item ENFILE
294 The entire system, or perhaps the file system which contains the
295 directory, cannot support any additional open files at the moment.
296 (This problem cannot happen on the GNU system.)
297 @end table
298
299 The @code{DIR} type is typically implemented using a file descriptor,
300 and the @code{opendir} function in terms of the @code{open} function.
301 @xref{Low-Level I/O}. Directory streams and the underlying
302 file descriptors are closed on @code{exec} (@pxref{Executing a File}).
303 @end deftypefun
304
305 @node Reading/Closing Directory
306 @subsection Reading and Closing a Directory Stream
307
308 @pindex dirent.h
309 This section describes how to read directory entries from a directory
310 stream, and how to close the stream when you are done with it. All the
311 symbols are declared in the header file @file{dirent.h}.
312
313 @comment dirent.h
314 @comment POSIX.1
315 @deftypefun {struct dirent *} readdir (DIR *@var{dirstream})
316 This function reads the next entry from the directory. It normally
317 returns a pointer to a structure containing information about the file.
318 This structure is statically allocated and can be rewritten by a
319 subsequent call.
320
321 @strong{Portability Note:} On some systems, @code{readdir} may not
322 return entries for @file{.} and @file{..}, even though these are always
323 valid file names in any directory. @xref{File Name Resolution}.
324
325 If there are no more entries in the directory or an error is detected,
326 @code{readdir} returns a null pointer. The following @code{errno} error
327 conditions are defined for this function:
328
329 @table @code
330 @item EBADF
331 The @var{dirstream} argument is not valid.
332 @end table
333
334 @code{readdir} is not thread safe. Multiple threads using
335 @code{readdir} on the same @var{dirstream} may overwrite the return
336 value. Use @code{readdir_r} when this is critical.
337 @end deftypefun
338
339 @comment dirent.h
340 @comment GNU
341 @deftypefun int readdir_r (DIR *@var{dirstream}, struct *@var{entry}, struct **@var{result})
342 This function is the reentrant version of @code{readdir}. Like
343 @code{readdir} it returns the next entry from the directory. But to
344 prevent conflicts for simultaneously running threads the result is not
345 stored in some internal memory. Instead the argument @var{entry} has to
346 point to a place where the result is stored.
347
348 The return value is @code{0} in case the next entry was read
349 successfully. In this case a pointer to the result is returned in
350 *@var{result}. It is not required that *@var{result} is the same as
351 @var{entry}. If something goes wrong while executing @code{readdir_r}
352 the function returns @code{-1}. The @code{errno} variable is set like
353 described for @code{readdir}.
354
355 @strong{Portability Note:} On some systems, @code{readdir_r} may not
356 return a terminated string as the file name even if no @code{d_reclen}
357 element is available in @code{struct dirent} and the file name as the
358 maximal allowed size. Modern systems all have the @code{d_reclen} field
359 and on old systems multi threading is not critical. In any case, there
360 is no such problem with the @code{readdir} function so that even on
361 systems without @code{d_reclen} field one could use multiple threads by
362 using external locking.
363 @end deftypefun
364
365 @comment dirent.h
366 @comment POSIX.1
367 @deftypefun int closedir (DIR *@var{dirstream})
368 This function closes the directory stream @var{dirstream}. It returns
369 @code{0} on success and @code{-1} on failure.
370
371 The following @code{errno} error conditions are defined for this
372 function:
373
374 @table @code
375 @item EBADF
376 The @var{dirstream} argument is not valid.
377 @end table
378 @end deftypefun
379
380 @node Simple Directory Lister
381 @subsection Simple Program to List a Directory
382
383 Here's a simple program that prints the names of the files in
384 the current working directory:
385
386 @smallexample
387 @include dir.c.texi
388 @end smallexample
389
390 The order in which files appear in a directory tends to be fairly
391 random. A more useful program would sort the entries (perhaps by
392 alphabetizing them) before printing them; see
393 @ref{Scanning Directory Content} and @ref{Array Sort Function}.
394
395
396 @node Random Access Directory
397 @subsection Random Access in a Directory Stream
398
399 @pindex dirent.h
400 This section describes how to reread parts of a directory that you have
401 already read from an open directory stream. All the symbols are
402 declared in the header file @file{dirent.h}.
403
404 @comment dirent.h
405 @comment POSIX.1
406 @deftypefun void rewinddir (DIR *@var{dirstream})
407 The @code{rewinddir} function is used to reinitialize the directory
408 stream @var{dirstream}, so that if you call @code{readdir} it
409 returns information about the first entry in the directory again. This
410 function also notices if files have been added or removed to the
411 directory since it was opened with @code{opendir}. (Entries for these
412 files might or might not be returned by @code{readdir} if they were
413 added or removed since you last called @code{opendir} or
414 @code{rewinddir}.)
415 @end deftypefun
416
417 @comment dirent.h
418 @comment BSD
419 @deftypefun off_t telldir (DIR *@var{dirstream})
420 The @code{telldir} function returns the file position of the directory
421 stream @var{dirstream}. You can use this value with @code{seekdir} to
422 restore the directory stream to that position.
423 @end deftypefun
424
425 @comment dirent.h
426 @comment BSD
427 @deftypefun void seekdir (DIR *@var{dirstream}, off_t @var{pos})
428 The @code{seekdir} function sets the file position of the directory
429 stream @var{dirstream} to @var{pos}. The value @var{pos} must be the
430 result of a previous call to @code{telldir} on this particular stream;
431 closing and reopening the directory can invalidate values returned by
432 @code{telldir}.
433 @end deftypefun
434
435
436 @node Scanning Directory Content
437 @subsection Scanning the Content of a Directory
438
439 A higher-level interface to the directory handling functions is the
440 @code{scandir} function. With its help one can select a subset of the
441 entries in a directory, possibly sort them and get as the result a list
442 of names.
443
444 @deftypefun int scandir (const char *@var{dir}, struct dirent ***@var{namelist}, int (*@var{selector}) (struct dirent *), int (*@var{cmp}) (const void *, const void *))
445
446 The @code{scandir} function scans the contents of the directory selected
447 by @var{dir}. The result in @var{namelist} is an array of pointers to
448 structure of type @code{struct dirent} which describe all selected
449 directory entries and which is allocated using @code{malloc}. Instead
450 of always getting all directory entries returned, the user supplied
451 function @var{selector} can be used to decide which entries are in the
452 result. Only the entries for which @var{selector} returns a nonzero
453 value are selected.
454
455 Finally the entries in the @var{namelist} are sorted using the user
456 supplied function @var{cmp}. The arguments of the @var{cmp} function
457 are of type @code{struct dirent **}. I.e., one cannot directly use the
458 @code{strcmp} or @code{strcoll} function; see the functions
459 @code{alphasort} and @code{versionsort} below.
460
461 The return value of the function gives the number of entries placed in
462 @var{namelist}. If it is @code{-1} an error occurred and the global
463 variable @code{errno} contains more information on the error.
464 @end deftypefun
465
466 As said above the fourth argument to the @code{scandir} function must be
467 a pointer to a sorting function. For the convenience of the programmer
468 the GNU C library contains implementations of functions which are very
469 helpful for this purpose.
470
471 @deftypefun int alphasort (const void *@var{a}, const void *@var{b})
472 The @code{alphasort} function behaves like the @code{strcmp} function
473 (@pxref{String/Array Comparison}). The difference is that the arguments
474 are not string pointers but instead they are of type
475 @code{struct dirent **}.
476
477 Return value of is less than, equal to, or greater than zero depending
478 on the order of the two entries @var{a} and @var{b}.
479 @end deftypefun
480
481 @deftypefun int versionsort (const void *@var{a}, const void *@var{b})
482 The @code{versionsort} function is like @code{alphasort}, excepted that it
483 uses the @code{strverscmp} function internally.
484 @end deftypefun
485
486 @node Simple Directory Lister Mark II
487 @subsection Simple Program to List a Directory, Mark II
488
489 Here is a revised version of the directory lister found above
490 (@pxref{Simple Directory Lister}). Using the @code{scandir} function we
491 can avoid using the functions which directly work with the directory
492 contents. After the call the found entries are available for direct
493 used.
494
495 @smallexample
496 @include dir2.c.texi
497 @end smallexample
498
499 Please note the simple selector function for this example. Since
500 we want to see all directory entries we always return @code{1}.
501
502
503 @node Hard Links
504 @section Hard Links
505 @cindex hard link
506 @cindex link, hard
507 @cindex multiple names for one file
508 @cindex file names, multiple
509
510 In POSIX systems, one file can have many names at the same time. All of
511 the names are equally real, and no one of them is preferred to the
512 others.
513
514 To add a name to a file, use the @code{link} function. (The new name is
515 also called a @dfn{hard link} to the file.) Creating a new link to a
516 file does not copy the contents of the file; it simply makes a new name
517 by which the file can be known, in addition to the file's existing name
518 or names.
519
520 One file can have names in several directories, so the the organization
521 of the file system is not a strict hierarchy or tree.
522
523 In most implementations, it is not possible to have hard links to the
524 same file in multiple file systems. @code{link} reports an error if you
525 try to make a hard link to the file from another file system when this
526 cannot be done.
527
528 The prototype for the @code{link} function is declared in the header
529 file @file{unistd.h}.
530 @pindex unistd.h
531
532 @comment unistd.h
533 @comment POSIX.1
534 @deftypefun int link (const char *@var{oldname}, const char *@var{newname})
535 The @code{link} function makes a new link to the existing file named by
536 @var{oldname}, under the new name @var{newname}.
537
538 This function returns a value of @code{0} if it is successful and
539 @code{-1} on failure. In addition to the usual file name errors
540 (@pxref{File Name Errors}) for both @var{oldname} and @var{newname}, the
541 following @code{errno} error conditions are defined for this function:
542
543 @table @code
544 @item EACCES
545 You are not allowed to write the directory in which the new link is to
546 be written.
547 @ignore
548 Some implementations also require that the existing file be accessible
549 by the caller, and use this error to report failure for that reason.
550 @end ignore
551
552 @item EEXIST
553 There is already a file named @var{newname}. If you want to replace
554 this link with a new link, you must remove the old link explicitly first.
555
556 @item EMLINK
557 There are already too many links to the file named by @var{oldname}.
558 (The maximum number of links to a file is @w{@code{LINK_MAX}}; see
559 @ref{Limits for Files}.)
560
561 @item ENOENT
562 The file named by @var{oldname} doesn't exist. You can't make a link to
563 a file that doesn't exist.
564
565 @item ENOSPC
566 The directory or file system that would contain the new link is full
567 and cannot be extended.
568
569 @item EPERM
570 In the GNU system and some others, you cannot make links to directories.
571 Many systems allow only privileged users to do so. This error
572 is used to report the problem.
573
574 @item EROFS
575 The directory containing the new link can't be modified because it's on
576 a read-only file system.
577
578 @item EXDEV
579 The directory specified in @var{newname} is on a different file system
580 than the existing file.
581
582 @item EIO
583 A hardware error occurred while trying to read or write the to filesystem.
584 @end table
585 @end deftypefun
586
587 @node Symbolic Links
588 @section Symbolic Links
589 @cindex soft link
590 @cindex link, soft
591 @cindex symbolic link
592 @cindex link, symbolic
593
594 The GNU system supports @dfn{soft links} or @dfn{symbolic links}. This
595 is a kind of ``file'' that is essentially a pointer to another file
596 name. Unlike hard links, symbolic links can be made to directories or
597 across file systems with no restrictions. You can also make a symbolic
598 link to a name which is not the name of any file. (Opening this link
599 will fail until a file by that name is created.) Likewise, if the
600 symbolic link points to an existing file which is later deleted, the
601 symbolic link continues to point to the same file name even though the
602 name no longer names any file.
603
604 The reason symbolic links work the way they do is that special things
605 happen when you try to open the link. The @code{open} function realizes
606 you have specified the name of a link, reads the file name contained in
607 the link, and opens that file name instead. The @code{stat} function
608 likewise operates on the file that the symbolic link points to, instead
609 of on the link itself.
610
611 By contrast, other operations such as deleting or renaming the file
612 operate on the link itself. The functions @code{readlink} and
613 @code{lstat} also refrain from following symbolic links, because their
614 purpose is to obtain information about the link. So does @code{link},
615 the function that makes a hard link---it makes a hard link to the
616 symbolic link, which one rarely wants.
617
618 Prototypes for the functions listed in this section are in
619 @file{unistd.h}.
620 @pindex unistd.h
621
622 @comment unistd.h
623 @comment BSD
624 @deftypefun int symlink (const char *@var{oldname}, const char *@var{newname})
625 The @code{symlink} function makes a symbolic link to @var{oldname} named
626 @var{newname}.
627
628 The normal return value from @code{symlink} is @code{0}. A return value
629 of @code{-1} indicates an error. In addition to the usual file name
630 syntax errors (@pxref{File Name Errors}), the following @code{errno}
631 error conditions are defined for this function:
632
633 @table @code
634 @item EEXIST
635 There is already an existing file named @var{newname}.
636
637 @item EROFS
638 The file @var{newname} would exist on a read-only file system.
639
640 @item ENOSPC
641 The directory or file system cannot be extended to make the new link.
642
643 @item EIO
644 A hardware error occurred while reading or writing data on the disk.
645
646 @ignore
647 @comment not sure about these
648 @item ELOOP
649 There are too many levels of indirection. This can be the result of
650 circular symbolic links to directories.
651
652 @item EDQUOT
653 The new link can't be created because the user's disk quota has been
654 exceeded.
655 @end ignore
656 @end table
657 @end deftypefun
658
659 @comment unistd.h
660 @comment BSD
661 @deftypefun int readlink (const char *@var{filename}, char *@var{buffer}, size_t @var{size})
662 The @code{readlink} function gets the value of the symbolic link
663 @var{filename}. The file name that the link points to is copied into
664 @var{buffer}. This file name string is @emph{not} null-terminated;
665 @code{readlink} normally returns the number of characters copied. The
666 @var{size} argument specifies the maximum number of characters to copy,
667 usually the allocation size of @var{buffer}.
668
669 If the return value equals @var{size}, you cannot tell whether or not
670 there was room to return the entire name. So make a bigger buffer and
671 call @code{readlink} again. Here is an example:
672
673 @smallexample
674 char *
675 readlink_malloc (char *filename)
676 @{
677 int size = 100;
678
679 while (1)
680 @{
681 char *buffer = (char *) xmalloc (size);
682 int nchars = readlink (filename, buffer, size);
683 if (nchars < size)
684 return buffer;
685 free (buffer);
686 size *= 2;
687 @}
688 @}
689 @end smallexample
690
691 @c @group Invalid outside example.
692 A value of @code{-1} is returned in case of error. In addition to the
693 usual file name errors (@pxref{File Name Errors}), the following
694 @code{errno} error conditions are defined for this function:
695
696 @table @code
697 @item EINVAL
698 The named file is not a symbolic link.
699
700 @item EIO
701 A hardware error occurred while reading or writing data on the disk.
702 @end table
703 @c @end group
704 @end deftypefun
705
706 @node Deleting Files
707 @section Deleting Files
708 @cindex deleting a file
709 @cindex removing a file
710 @cindex unlinking a file
711
712 You can delete a file with the functions @code{unlink} or @code{remove}.
713
714 Deletion actually deletes a file name. If this is the file's only name,
715 then the file is deleted as well. If the file has other names as well
716 (@pxref{Hard Links}), it remains accessible under its other names.
717
718 @comment unistd.h
719 @comment POSIX.1
720 @deftypefun int unlink (const char *@var{filename})
721 The @code{unlink} function deletes the file name @var{filename}. If
722 this is a file's sole name, the file itself is also deleted. (Actually,
723 if any process has the file open when this happens, deletion is
724 postponed until all processes have closed the file.)
725
726 @pindex unistd.h
727 The function @code{unlink} is declared in the header file @file{unistd.h}.
728
729 This function returns @code{0} on successful completion, and @code{-1}
730 on error. In addition to the usual file name errors
731 (@pxref{File Name Errors}), the following @code{errno} error conditions are
732 defined for this function:
733
734 @table @code
735 @item EACCES
736 Write permission is denied for the directory from which the file is to be
737 removed, or the directory has the sticky bit set and you do not own the file.
738
739 @item EBUSY
740 This error indicates that the file is being used by the system in such a
741 way that it can't be unlinked. For example, you might see this error if
742 the file name specifies the root directory or a mount point for a file
743 system.
744
745 @item ENOENT
746 The file name to be deleted doesn't exist.
747
748 @item EPERM
749 On some systems, @code{unlink} cannot be used to delete the name of a
750 directory, or can only be used this way by a privileged user.
751 To avoid such problems, use @code{rmdir} to delete directories.
752 (In the GNU system @code{unlink} can never delete the name of a directory.)
753
754 @item EROFS
755 The directory in which the file name is to be deleted is on a read-only
756 file system, and can't be modified.
757 @end table
758 @end deftypefun
759
760 @comment unistd.h
761 @comment POSIX.1
762 @deftypefun int rmdir (const char *@var{filename})
763 @cindex directories, deleting
764 @cindex deleting a directory
765 The @code{rmdir} function deletes a directory. The directory must be
766 empty before it can be removed; in other words, it can only contain
767 entries for @file{.} and @file{..}.
768
769 In most other respects, @code{rmdir} behaves like @code{unlink}. There
770 are two additional @code{errno} error conditions defined for
771 @code{rmdir}:
772
773 @table @code
774 @item ENOTEMPTY
775 @itemx EEXIST
776 The directory to be deleted is not empty.
777 @end table
778
779 These two error codes are synonymous; some systems use one, and some use
780 the other. The GNU system always uses @code{ENOTEMPTY}.
781
782 The prototype for this function is declared in the header file
783 @file{unistd.h}.
784 @pindex unistd.h
785 @end deftypefun
786
787 @comment stdio.h
788 @comment ISO
789 @deftypefun int remove (const char *@var{filename})
790 This is the @w{ISO C} function to remove a file. It works like
791 @code{unlink} for files and like @code{rmdir} for directories.
792 @code{remove} is declared in @file{stdio.h}.
793 @pindex stdio.h
794 @end deftypefun
795
796 @node Renaming Files
797 @section Renaming Files
798
799 The @code{rename} function is used to change a file's name.
800
801 @cindex renaming a file
802 @comment stdio.h
803 @comment ISO
804 @deftypefun int rename (const char *@var{oldname}, const char *@var{newname})
805 The @code{rename} function renames the file name @var{oldname} with
806 @var{newname}. The file formerly accessible under the name
807 @var{oldname} is afterward accessible as @var{newname} instead. (If the
808 file had any other names aside from @var{oldname}, it continues to have
809 those names.)
810
811 The directory containing the name @var{newname} must be on the same
812 file system as the file (as indicated by the name @var{oldname}).
813
814 One special case for @code{rename} is when @var{oldname} and
815 @var{newname} are two names for the same file. The consistent way to
816 handle this case is to delete @var{oldname}. However, POSIX requires
817 that in this case @code{rename} do nothing and report success---which is
818 inconsistent. We don't know what your operating system will do.
819
820 If the @var{oldname} is not a directory, then any existing file named
821 @var{newname} is removed during the renaming operation. However, if
822 @var{newname} is the name of a directory, @code{rename} fails in this
823 case.
824
825 If the @var{oldname} is a directory, then either @var{newname} must not
826 exist or it must name a directory that is empty. In the latter case,
827 the existing directory named @var{newname} is deleted first. The name
828 @var{newname} must not specify a subdirectory of the directory
829 @code{oldname} which is being renamed.
830
831 One useful feature of @code{rename} is that the meaning of the name
832 @var{newname} changes ``atomically'' from any previously existing file
833 by that name to its new meaning (the file that was called
834 @var{oldname}). There is no instant at which @var{newname} is
835 nonexistent ``in between'' the old meaning and the new meaning. If
836 there is a system crash during the operation, it is possible for both
837 names to still exist; but @var{newname} will always be intact if it
838 exists at all.
839
840 If @code{rename} fails, it returns @code{-1}. In addition to the usual
841 file name errors (@pxref{File Name Errors}), the following
842 @code{errno} error conditions are defined for this function:
843
844 @table @code
845 @item EACCES
846 One of the directories containing @var{newname} or @var{oldname}
847 refuses write permission; or @var{newname} and @var{oldname} are
848 directories and write permission is refused for one of them.
849
850 @item EBUSY
851 A directory named by @var{oldname} or @var{newname} is being used by
852 the system in a way that prevents the renaming from working. This includes
853 directories that are mount points for filesystems, and directories
854 that are the current working directories of processes.
855
856 @item ENOTEMPTY
857 @itemx EEXIST
858 The directory @var{newname} isn't empty. The GNU system always returns
859 @code{ENOTEMPTY} for this, but some other systems return @code{EEXIST}.
860
861 @item EINVAL
862 The @var{oldname} is a directory that contains @var{newname}.
863
864 @item EISDIR
865 The @var{newname} names a directory, but the @var{oldname} doesn't.
866
867 @item EMLINK
868 The parent directory of @var{newname} would have too many links.
869
870 @item ENOENT
871 The file named by @var{oldname} doesn't exist.
872
873 @item ENOSPC
874 The directory that would contain @var{newname} has no room for another
875 entry, and there is no space left in the file system to expand it.
876
877 @item EROFS
878 The operation would involve writing to a directory on a read-only file
879 system.
880
881 @item EXDEV
882 The two file names @var{newname} and @var{oldnames} are on different
883 file systems.
884 @end table
885 @end deftypefun
886
887 @node Creating Directories
888 @section Creating Directories
889 @cindex creating a directory
890 @cindex directories, creating
891
892 @pindex mkdir
893 Directories are created with the @code{mkdir} function. (There is also
894 a shell command @code{mkdir} which does the same thing.)
895 @c !!! umask
896
897 @comment sys/stat.h
898 @comment POSIX.1
899 @deftypefun int mkdir (const char *@var{filename}, mode_t @var{mode})
900 The @code{mkdir} function creates a new, empty directory whose name is
901 @var{filename}.
902
903 The argument @var{mode} specifies the file permissions for the new
904 directory file. @xref{Permission Bits}, for more information about
905 this.
906
907 A return value of @code{0} indicates successful completion, and
908 @code{-1} indicates failure. In addition to the usual file name syntax
909 errors (@pxref{File Name Errors}), the following @code{errno} error
910 conditions are defined for this function:
911
912 @table @code
913 @item EACCES
914 Write permission is denied for the parent directory in which the new
915 directory is to be added.
916
917 @item EEXIST
918 A file named @var{filename} already exists.
919
920 @item EMLINK
921 The parent directory has too many links.
922
923 Well-designed file systems never report this error, because they permit
924 more links than your disk could possibly hold. However, you must still
925 take account of the possibility of this error, as it could result from
926 network access to a file system on another machine.
927
928 @item ENOSPC
929 The file system doesn't have enough room to create the new directory.
930
931 @item EROFS
932 The parent directory of the directory being created is on a read-only
933 file system, and cannot be modified.
934 @end table
935
936 To use this function, your program should include the header file
937 @file{sys/stat.h}.
938 @pindex sys/stat.h
939 @end deftypefun
940
941 @node File Attributes
942 @section File Attributes
943
944 @pindex ls
945 When you issue an @samp{ls -l} shell command on a file, it gives you
946 information about the size of the file, who owns it, when it was last
947 modified, and the like. This kind of information is called the
948 @dfn{file attributes}; it is associated with the file itself and not a
949 particular one of its names.
950
951 This section contains information about how you can inquire about and
952 modify these attributes of files.
953
954 @menu
955 * Attribute Meanings:: The names of the file attributes,
956 and what their values mean.
957 * Reading Attributes:: How to read the attributes of a file.
958 * Testing File Type:: Distinguishing ordinary files,
959 directories, links...
960 * File Owner:: How ownership for new files is determined,
961 and how to change it.
962 * Permission Bits:: How information about a file's access
963 mode is stored.
964 * Access Permission:: How the system decides who can access a file.
965 * Setting Permissions:: How permissions for new files are assigned,
966 and how to change them.
967 * Testing File Access:: How to find out if your process can
968 access a file.
969 * File Times:: About the time attributes of a file.
970 @end menu
971
972 @node Attribute Meanings
973 @subsection What the File Attribute Values Mean
974 @cindex status of a file
975 @cindex attributes of a file
976 @cindex file attributes
977
978 When you read the attributes of a file, they come back in a structure
979 called @code{struct stat}. This section describes the names of the
980 attributes, their data types, and what they mean. For the functions
981 to read the attributes of a file, see @ref{Reading Attributes}.
982
983 The header file @file{sys/stat.h} declares all the symbols defined
984 in this section.
985 @pindex sys/stat.h
986
987 @comment sys/stat.h
988 @comment POSIX.1
989 @deftp {Data Type} {struct stat}
990 The @code{stat} structure type is used to return information about the
991 attributes of a file. It contains at least the following members:
992
993 @table @code
994 @item mode_t st_mode
995 Specifies the mode of the file. This includes file type information
996 (@pxref{Testing File Type}) and the file permission bits
997 (@pxref{Permission Bits}).
998
999 @item ino_t st_ino
1000 The file serial number, which distinguishes this file from all other
1001 files on the same device.
1002
1003 @item dev_t st_dev
1004 Identifies the device containing the file. The @code{st_ino} and
1005 @code{st_dev}, taken together, uniquely identify the file. The
1006 @code{st_dev} value is not necessarily consistent across reboots or
1007 system crashes, however.
1008
1009 @item nlink_t st_nlink
1010 The number of hard links to the file. This count keeps track of how
1011 many directories have entries for this file. If the count is ever
1012 decremented to zero, then the file itself is discarded as soon as no
1013 process still holds it open. Symbolic links are not counted in the
1014 total.
1015
1016 @item uid_t st_uid
1017 The user ID of the file's owner. @xref{File Owner}.
1018
1019 @item gid_t st_gid
1020 The group ID of the file. @xref{File Owner}.
1021
1022 @item off_t st_size
1023 This specifies the size of a regular file in bytes. For files that
1024 are really devices and the like, this field isn't usually meaningful.
1025 For symbolic links, this specifies the length of the file name the link
1026 refers to.
1027
1028 @item time_t st_atime
1029 This is the last access time for the file. @xref{File Times}.
1030
1031 @item unsigned long int st_atime_usec
1032 This is the fractional part of the last access time for the file.
1033 @xref{File Times}.
1034
1035 @item time_t st_mtime
1036 This is the time of the last modification to the contents of the file.
1037 @xref{File Times}.
1038
1039 @item unsigned long int st_mtime_usec
1040 This is the fractional part of the time of last modification to the
1041 contents of the file. @xref{File Times}.
1042
1043 @item time_t st_ctime
1044 This is the time of the last modification to the attributes of the file.
1045 @xref{File Times}.
1046
1047 @item unsigned long int st_ctime_usec
1048 This is the fractional part of the time of last modification to the
1049 attributes of the file. @xref{File Times}.
1050
1051 @c !!! st_rdev
1052 @item unsigned int st_blocks
1053 This is the amount of disk space that the file occupies, measured in
1054 units of 512-byte blocks.
1055
1056 The number of disk blocks is not strictly proportional to the size of
1057 the file, for two reasons: the file system may use some blocks for
1058 internal record keeping; and the file may be sparse---it may have
1059 ``holes'' which contain zeros but do not actually take up space on the
1060 disk.
1061
1062 You can tell (approximately) whether a file is sparse by comparing this
1063 value with @code{st_size}, like this:
1064
1065 @smallexample
1066 (st.st_blocks * 512 < st.st_size)
1067 @end smallexample
1068
1069 This test is not perfect because a file that is just slightly sparse
1070 might not be detected as sparse at all. For practical applications,
1071 this is not a problem.
1072
1073 @item unsigned int st_blksize
1074 The optimal block size for reading of writing this file, in bytes. You
1075 might use this size for allocating the buffer space for reading of
1076 writing the file. (This is unrelated to @code{st_blocks}.)
1077 @end table
1078 @end deftp
1079
1080 Some of the file attributes have special data type names which exist
1081 specifically for those attributes. (They are all aliases for well-known
1082 integer types that you know and love.) These typedef names are defined
1083 in the header file @file{sys/types.h} as well as in @file{sys/stat.h}.
1084 Here is a list of them.
1085
1086 @comment sys/types.h
1087 @comment POSIX.1
1088 @deftp {Data Type} mode_t
1089 This is an integer data type used to represent file modes. In the
1090 GNU system, this is equivalent to @code{unsigned int}.
1091 @end deftp
1092
1093 @cindex inode number
1094 @comment sys/types.h
1095 @comment POSIX.1
1096 @deftp {Data Type} ino_t
1097 This is an arithmetic data type used to represent file serial numbers.
1098 (In Unix jargon, these are sometimes called @dfn{inode numbers}.)
1099 In the GNU system, this type is equivalent to @code{unsigned long int}.
1100 @end deftp
1101
1102 @comment sys/types.h
1103 @comment POSIX.1
1104 @deftp {Data Type} dev_t
1105 This is an arithmetic data type used to represent file device numbers.
1106 In the GNU system, this is equivalent to @code{int}.
1107 @end deftp
1108
1109 @comment sys/types.h
1110 @comment POSIX.1
1111 @deftp {Data Type} nlink_t
1112 This is an arithmetic data type used to represent file link counts.
1113 In the GNU system, this is equivalent to @code{unsigned short int}.
1114 @end deftp
1115
1116 @node Reading Attributes
1117 @subsection Reading the Attributes of a File
1118
1119 To examine the attributes of files, use the functions @code{stat},
1120 @code{fstat} and @code{lstat}. They return the attribute information in
1121 a @code{struct stat} object. All three functions are declared in the
1122 header file @file{sys/stat.h}.
1123
1124 @comment sys/stat.h
1125 @comment POSIX.1
1126 @deftypefun int stat (const char *@var{filename}, struct stat *@var{buf})
1127 The @code{stat} function returns information about the attributes of the
1128 file named by @w{@var{filename}} in the structure pointed at by @var{buf}.
1129
1130 If @var{filename} is the name of a symbolic link, the attributes you get
1131 describe the file that the link points to. If the link points to a
1132 nonexistent file name, then @code{stat} fails, reporting a nonexistent
1133 file.
1134
1135 The return value is @code{0} if the operation is successful, and @code{-1}
1136 on failure. In addition to the usual file name errors
1137 (@pxref{File Name Errors}, the following @code{errno} error conditions
1138 are defined for this function:
1139
1140 @table @code
1141 @item ENOENT
1142 The file named by @var{filename} doesn't exist.
1143 @end table
1144 @end deftypefun
1145
1146 @comment sys/stat.h
1147 @comment POSIX.1
1148 @deftypefun int fstat (int @var{filedes}, struct stat *@var{buf})
1149 The @code{fstat} function is like @code{stat}, except that it takes an
1150 open file descriptor as an argument instead of a file name.
1151 @xref{Low-Level I/O}.
1152
1153 Like @code{stat}, @code{fstat} returns @code{0} on success and @code{-1}
1154 on failure. The following @code{errno} error conditions are defined for
1155 @code{fstat}:
1156
1157 @table @code
1158 @item EBADF
1159 The @var{filedes} argument is not a valid file descriptor.
1160 @end table
1161 @end deftypefun
1162
1163 @comment sys/stat.h
1164 @comment BSD
1165 @deftypefun int lstat (const char *@var{filename}, struct stat *@var{buf})
1166 The @code{lstat} function is like @code{stat}, except that it does not
1167 follow symbolic links. If @var{filename} is the name of a symbolic
1168 link, @code{lstat} returns information about the link itself; otherwise,
1169 @code{lstat} works like @code{stat}. @xref{Symbolic Links}.
1170 @end deftypefun
1171
1172 @node Testing File Type
1173 @subsection Testing the Type of a File
1174
1175 The @dfn{file mode}, stored in the @code{st_mode} field of the file
1176 attributes, contains two kinds of information: the file type code, and
1177 the access permission bits. This section discusses only the type code,
1178 which you can use to tell whether the file is a directory, whether it is
1179 a socket, and so on. For information about the access permission,
1180 @ref{Permission Bits}.
1181
1182 There are two predefined ways you can access the file type portion of
1183 the file mode. First of all, for each type of file, there is a
1184 @dfn{predicate macro} which examines a file mode value and returns
1185 true or false---is the file of that type, or not. Secondly, you can
1186 mask out the rest of the file mode to get just a file type code.
1187 You can compare this against various constants for the supported file
1188 types.
1189
1190 All of the symbols listed in this section are defined in the header file
1191 @file{sys/stat.h}.
1192 @pindex sys/stat.h
1193
1194 The following predicate macros test the type of a file, given the value
1195 @var{m} which is the @code{st_mode} field returned by @code{stat} on
1196 that file:
1197
1198 @comment sys/stat.h
1199 @comment POSIX
1200 @deftypefn Macro int S_ISDIR (mode_t @var{m})
1201 This macro returns nonzero if the file is a directory.
1202 @end deftypefn
1203
1204 @comment sys/stat.h
1205 @comment POSIX
1206 @deftypefn Macro int S_ISCHR (mode_t @var{m})
1207 This macro returns nonzero if the file is a character special file (a
1208 device like a terminal).
1209 @end deftypefn
1210
1211 @comment sys/stat.h
1212 @comment POSIX
1213 @deftypefn Macro int S_ISBLK (mode_t @var{m})
1214 This macro returns nonzero if the file is a block special file (a device
1215 like a disk).
1216 @end deftypefn
1217
1218 @comment sys/stat.h
1219 @comment POSIX
1220 @deftypefn Macro int S_ISREG (mode_t @var{m})
1221 This macro returns nonzero if the file is a regular file.
1222 @end deftypefn
1223
1224 @comment sys/stat.h
1225 @comment POSIX
1226 @deftypefn Macro int S_ISFIFO (mode_t @var{m})
1227 This macro returns nonzero if the file is a FIFO special file, or a
1228 pipe. @xref{Pipes and FIFOs}.
1229 @end deftypefn
1230
1231 @comment sys/stat.h
1232 @comment GNU
1233 @deftypefn Macro int S_ISLNK (mode_t @var{m})
1234 This macro returns nonzero if the file is a symbolic link.
1235 @xref{Symbolic Links}.
1236 @end deftypefn
1237
1238 @comment sys/stat.h
1239 @comment GNU
1240 @deftypefn Macro int S_ISSOCK (mode_t @var{m})
1241 This macro returns nonzero if the file is a socket. @xref{Sockets}.
1242 @end deftypefn
1243
1244 An alterate non-POSIX method of testing the file type is supported for
1245 compatibility with BSD. The mode can be bitwise ANDed with
1246 @code{S_IFMT} to extract the file type code, and compared to the
1247 appropriate type code constant. For example,
1248
1249 @smallexample
1250 S_ISCHR (@var{mode})
1251 @end smallexample
1252
1253 @noindent
1254 is equivalent to:
1255
1256 @smallexample
1257 ((@var{mode} & S_IFMT) == S_IFCHR)
1258 @end smallexample
1259
1260 @comment sys/stat.h
1261 @comment BSD
1262 @deftypevr Macro int S_IFMT
1263 This is a bit mask used to extract the file type code portion of a mode
1264 value.
1265 @end deftypevr
1266
1267 These are the symbolic names for the different file type codes:
1268
1269 @table @code
1270 @comment sys/stat.h
1271 @comment BSD
1272 @item S_IFDIR
1273 @vindex S_IFDIR
1274 This macro represents the value of the file type code for a directory file.
1275
1276 @comment sys/stat.h
1277 @comment BSD
1278 @item S_IFCHR
1279 @vindex S_IFCHR
1280 This macro represents the value of the file type code for a
1281 character-oriented device file.
1282
1283 @comment sys/stat.h
1284 @comment BSD
1285 @item S_IFBLK
1286 @vindex S_IFBLK
1287 This macro represents the value of the file type code for a block-oriented
1288 device file.
1289
1290 @comment sys/stat.h
1291 @comment BSD
1292 @item S_IFREG
1293 @vindex S_IFREG
1294 This macro represents the value of the file type code for a regular file.
1295
1296 @comment sys/stat.h
1297 @comment BSD
1298 @item S_IFLNK
1299 @vindex S_IFLNK
1300 This macro represents the value of the file type code for a symbolic link.
1301
1302 @comment sys/stat.h
1303 @comment BSD
1304 @item S_IFSOCK
1305 @vindex S_IFSOCK
1306 This macro represents the value of the file type code for a socket.
1307
1308 @comment sys/stat.h
1309 @comment BSD
1310 @item S_IFIFO
1311 @vindex S_IFIFO
1312 This macro represents the value of the file type code for a FIFO or pipe.
1313 @end table
1314
1315 @node File Owner
1316 @subsection File Owner
1317 @cindex file owner
1318 @cindex owner of a file
1319 @cindex group owner of a file
1320
1321 Every file has an @dfn{owner} which is one of the registered user names
1322 defined on the system. Each file also has a @dfn{group}, which is one
1323 of the defined groups. The file owner can often be useful for showing
1324 you who edited the file (especially when you edit with GNU Emacs), but
1325 its main purpose is for access control.
1326
1327 The file owner and group play a role in determining access because the
1328 file has one set of access permission bits for the user that is the
1329 owner, another set that apply to users who belong to the file's group,
1330 and a third set of bits that apply to everyone else. @xref{Access
1331 Permission}, for the details of how access is decided based on this
1332 data.
1333
1334 When a file is created, its owner is set from the effective user ID of
1335 the process that creates it (@pxref{Process Persona}). The file's group
1336 ID may be set from either effective group ID of the process, or the
1337 group ID of the directory that contains the file, depending on the
1338 system where the file is stored. When you access a remote file system,
1339 it behaves according to its own rule, not according to the system your
1340 program is running on. Thus, your program must be prepared to encounter
1341 either kind of behavior, no matter what kind of system you run it on.
1342
1343 @pindex chown
1344 @pindex chgrp
1345 You can change the owner and/or group owner of an existing file using
1346 the @code{chown} function. This is the primitive for the @code{chown}
1347 and @code{chgrp} shell commands.
1348
1349 @pindex unistd.h
1350 The prototype for this function is declared in @file{unistd.h}.
1351
1352 @comment unistd.h
1353 @comment POSIX.1
1354 @deftypefun int chown (const char *@var{filename}, uid_t @var{owner}, gid_t @var{group})
1355 The @code{chown} function changes the owner of the file @var{filename} to
1356 @var{owner}, and its group owner to @var{group}.
1357
1358 Changing the owner of the file on certain systems clears the set-user-ID
1359 and set-group-ID bits of the file's permissions. (This is because those
1360 bits may not be appropriate for the new owner.) The other file
1361 permission bits are not changed.
1362
1363 The return value is @code{0} on success and @code{-1} on failure.
1364 In addition to the usual file name errors (@pxref{File Name Errors}),
1365 the following @code{errno} error conditions are defined for this function:
1366
1367 @table @code
1368 @item EPERM
1369 This process lacks permission to make the requested change.
1370
1371 Only privileged users or the file's owner can change the file's group.
1372 On most file systems, only privileged users can change the file owner;
1373 some file systems allow you to change the owner if you are currently the
1374 owner. When you access a remote file system, the behavior you encounter
1375 is determined by the system that actually holds the file, not by the
1376 system your program is running on.
1377
1378 @xref{Options for Files}, for information about the
1379 @code{_POSIX_CHOWN_RESTRICTED} macro.
1380
1381 @item EROFS
1382 The file is on a read-only file system.
1383 @end table
1384 @end deftypefun
1385
1386 @comment unistd.h
1387 @comment BSD
1388 @deftypefun int fchown (int @var{filedes}, int @var{owner}, int @var{group})
1389 This is like @code{chown}, except that it changes the owner of the file
1390 with open file descriptor @var{filedes}.
1391
1392 The return value from @code{fchown} is @code{0} on success and @code{-1}
1393 on failure. The following @code{errno} error codes are defined for this
1394 function:
1395
1396 @table @code
1397 @item EBADF
1398 The @var{filedes} argument is not a valid file descriptor.
1399
1400 @item EINVAL
1401 The @var{filedes} argument corresponds to a pipe or socket, not an ordinary
1402 file.
1403
1404 @item EPERM
1405 This process lacks permission to make the requested change. For
1406 details, see @code{chmod}, above.
1407
1408 @item EROFS
1409 The file resides on a read-only file system.
1410 @end table
1411 @end deftypefun
1412
1413 @node Permission Bits
1414 @subsection The Mode Bits for Access Permission
1415
1416 The @dfn{file mode}, stored in the @code{st_mode} field of the file
1417 attributes, contains two kinds of information: the file type code, and
1418 the access permission bits. This section discusses only the access
1419 permission bits, which control who can read or write the file.
1420 @xref{Testing File Type}, for information about the file type code.
1421
1422 All of the symbols listed in this section are defined in the header file
1423 @file{sys/stat.h}.
1424 @pindex sys/stat.h
1425
1426 @cindex file permission bits
1427 These symbolic constants are defined for the file mode bits that control
1428 access permission for the file:
1429
1430 @table @code
1431 @comment sys/stat.h
1432 @comment POSIX.1
1433 @item S_IRUSR
1434 @vindex S_IRUSR
1435 @comment sys/stat.h
1436 @comment BSD
1437 @itemx S_IREAD
1438 @vindex S_IREAD
1439 Read permission bit for the owner of the file. On many systems, this
1440 bit is 0400. @code{S_IREAD} is an obsolete synonym provided for BSD
1441 compatibility.
1442
1443 @comment sys/stat.h
1444 @comment POSIX.1
1445 @item S_IWUSR
1446 @vindex S_IWUSR
1447 @comment sys/stat.h
1448 @comment BSD
1449 @itemx S_IWRITE
1450 @vindex S_IWRITE
1451 Write permission bit for the owner of the file. Usually 0200.
1452 @w{@code{S_IWRITE}} is an obsolete synonym provided for BSD compatibility.
1453
1454 @comment sys/stat.h
1455 @comment POSIX.1
1456 @item S_IXUSR
1457 @vindex S_IXUSR
1458 @comment sys/stat.h
1459 @comment BSD
1460 @itemx S_IEXEC
1461 @vindex S_IEXEC
1462 Execute (for ordinary files) or search (for directories) permission bit
1463 for the owner of the file. Usually 0100. @code{S_IEXEC} is an obsolete
1464 synonym provided for BSD compatibility.
1465
1466 @comment sys/stat.h
1467 @comment POSIX.1
1468 @item S_IRWXU
1469 @vindex S_IRWXU
1470 This is equivalent to @samp{(S_IRUSR | S_IWUSR | S_IXUSR)}.
1471
1472 @comment sys/stat.h
1473 @comment POSIX.1
1474 @item S_IRGRP
1475 @vindex S_IRGRP
1476 Read permission bit for the group owner of the file. Usually 040.
1477
1478 @comment sys/stat.h
1479 @comment POSIX.1
1480 @item S_IWGRP
1481 @vindex S_IWGRP
1482 Write permission bit for the group owner of the file. Usually 020.
1483
1484 @comment sys/stat.h
1485 @comment POSIX.1
1486 @item S_IXGRP
1487 @vindex S_IXGRP
1488 Execute or search permission bit for the group owner of the file.
1489 Usually 010.
1490
1491 @comment sys/stat.h
1492 @comment POSIX.1
1493 @item S_IRWXG
1494 @vindex S_IRWXG
1495 This is equivalent to @samp{(S_IRGRP | S_IWGRP | S_IXGRP)}.
1496
1497 @comment sys/stat.h
1498 @comment POSIX.1
1499 @item S_IROTH
1500 @vindex S_IROTH
1501 Read permission bit for other users. Usually 04.
1502
1503 @comment sys/stat.h
1504 @comment POSIX.1
1505 @item S_IWOTH
1506 @vindex S_IWOTH
1507 Write permission bit for other users. Usually 02.
1508
1509 @comment sys/stat.h
1510 @comment POSIX.1
1511 @item S_IXOTH
1512 @vindex S_IXOTH
1513 Execute or search permission bit for other users. Usually 01.
1514
1515 @comment sys/stat.h
1516 @comment POSIX.1
1517 @item S_IRWXO
1518 @vindex S_IRWXO
1519 This is equivalent to @samp{(S_IROTH | S_IWOTH | S_IXOTH)}.
1520
1521 @comment sys/stat.h
1522 @comment POSIX
1523 @item S_ISUID
1524 @vindex S_ISUID
1525 This is the set-user-ID on execute bit, usually 04000.
1526 @xref{How Change Persona}.
1527
1528 @comment sys/stat.h
1529 @comment POSIX
1530 @item S_ISGID
1531 @vindex S_ISGID
1532 This is the set-group-ID on execute bit, usually 02000.
1533 @xref{How Change Persona}.
1534
1535 @cindex sticky bit
1536 @comment sys/stat.h
1537 @comment BSD
1538 @item S_ISVTX
1539 @vindex S_ISVTX
1540 This is the @dfn{sticky} bit, usually 01000.
1541
1542 On a directory, it gives permission to delete a file in the directory
1543 only if you own that file. Ordinarily, a user either can delete all the
1544 files in the directory or cannot delete any of them (based on whether
1545 the user has write permission for the directory). The same restriction
1546 applies---you must both have write permission for the directory and own
1547 the file you want to delete. The one exception is that the owner of the
1548 directory can delete any file in the directory, no matter who owns it
1549 (provided the owner has given himself write permission for the
1550 directory). This is commonly used for the @file{/tmp} directory, where
1551 anyone may create files, but not delete files created by other users.
1552
1553 Originally the sticky bit on an executable file modified the swapping
1554 policies of the system. Normally, when a program terminated, its pages
1555 in core were immediately freed and reused. If the sticky bit was set on
1556 the executable file, the system kept the pages in core for a while as if
1557 the program were still running. This was advantageous for a program
1558 likely to be run many times in succession. This usage is obsolete in
1559 modern systems. When a program terminates, its pages always remain in
1560 core as long as there is no shortage of memory in the system. When the
1561 program is next run, its pages will still be in core if no shortage
1562 arose since the last run.
1563
1564 On some modern systems where the sticky bit has no useful meaning for an
1565 executable file, you cannot set the bit at all for a non-directory.
1566 If you try, @code{chmod} fails with @code{EFTYPE};
1567 @pxref{Setting Permissions}.
1568
1569 Some systems (particularly SunOS) have yet another use for the sticky
1570 bit. If the sticky bit is set on a file that is @emph{not} executable,
1571 it means the opposite: never cache the pages of this file at all. The
1572 main use of this is for the files on an NFS server machine which are
1573 used as the swap area of diskless client machines. The idea is that the
1574 pages of the file will be cached in the client's memory, so it is a
1575 waste of the server's memory to cache them a second time. In this use
1576 the sticky bit also says that the filesystem may fail to record the
1577 file's modification time onto disk reliably (the idea being that noone
1578 cares for a swap file).
1579 @end table
1580
1581 The actual bit values of the symbols are listed in the table above
1582 so you can decode file mode values when debugging your programs.
1583 These bit values are correct for most systems, but they are not
1584 guaranteed.
1585
1586 @strong{Warning:} Writing explicit numbers for file permissions is bad
1587 practice. It is not only nonportable, it also requires everyone who
1588 reads your program to remember what the bits mean. To make your
1589 program clean, use the symbolic names.
1590
1591 @node Access Permission
1592 @subsection How Your Access to a File is Decided
1593 @cindex permission to access a file
1594 @cindex access permission for a file
1595 @cindex file access permission
1596
1597 Recall that the operating system normally decides access permission for
1598 a file based on the effective user and group IDs of the process, and its
1599 supplementary group IDs, together with the file's owner, group and
1600 permission bits. These concepts are discussed in detail in
1601 @ref{Process Persona}.
1602
1603 If the effective user ID of the process matches the owner user ID of the
1604 file, then permissions for read, write, and execute/search are
1605 controlled by the corresponding ``user'' (or ``owner'') bits. Likewise,
1606 if any of the effective group ID or supplementary group IDs of the
1607 process matches the group owner ID of the file, then permissions are
1608 controlled by the ``group'' bits. Otherwise, permissions are controlled
1609 by the ``other'' bits.
1610
1611 Privileged users, like @samp{root}, can access any file, regardless of
1612 its file permission bits. As a special case, for a file to be
1613 executable even for a privileged user, at least one of its execute bits
1614 must be set.
1615
1616 @node Setting Permissions
1617 @subsection Assigning File Permissions
1618
1619 @cindex file creation mask
1620 @cindex umask
1621 The primitive functions for creating files (for example, @code{open} or
1622 @code{mkdir}) take a @var{mode} argument, which specifies the file
1623 permissions for the newly created file. But the specified mode is
1624 modified by the process's @dfn{file creation mask}, or @dfn{umask},
1625 before it is used.
1626
1627 The bits that are set in the file creation mask identify permissions
1628 that are always to be disabled for newly created files. For example, if
1629 you set all the ``other'' access bits in the mask, then newly created
1630 files are not accessible at all to processes in the ``other''
1631 category, even if the @var{mode} argument specified to the creation
1632 function would permit such access. In other words, the file creation
1633 mask is the complement of the ordinary access permissions you want to
1634 grant.
1635
1636 Programs that create files typically specify a @var{mode} argument that
1637 includes all the permissions that make sense for the particular file.
1638 For an ordinary file, this is typically read and write permission for
1639 all classes of users. These permissions are then restricted as
1640 specified by the individual user's own file creation mask.
1641
1642 @findex chmod
1643 To change the permission of an existing file given its name, call
1644 @code{chmod}. This function ignores the file creation mask; it uses
1645 exactly the specified permission bits.
1646
1647 @pindex umask
1648 In normal use, the file creation mask is initialized in the user's login
1649 shell (using the @code{umask} shell command), and inherited by all
1650 subprocesses. Application programs normally don't need to worry about
1651 the file creation mask. It will do automatically what it is supposed to
1652 do.
1653
1654 When your program should create a file and bypass the umask for its
1655 access permissions, the easiest way to do this is to use @code{fchmod}
1656 after opening the file, rather than changing the umask.
1657
1658 In fact, changing the umask is usually done only by shells. They use
1659 the @code{umask} function.
1660
1661 The functions in this section are declared in @file{sys/stat.h}.
1662 @pindex sys/stat.h
1663
1664 @comment sys/stat.h
1665 @comment POSIX.1
1666 @deftypefun mode_t umask (mode_t @var{mask})
1667 The @code{umask} function sets the file creation mask of the current
1668 process to @var{mask}, and returns the previous value of the file
1669 creation mask.
1670
1671 Here is an example showing how to read the mask with @code{umask}
1672 without changing it permanently:
1673
1674 @smallexample
1675 mode_t
1676 read_umask (void)
1677 @{
1678 mask = umask (0);
1679 umask (mask);
1680 @}
1681 @end smallexample
1682
1683 @noindent
1684 However, it is better to use @code{getumask} if you just want to read
1685 the mask value, because that is reentrant (at least if you use the GNU
1686 operating system).
1687 @end deftypefun
1688
1689 @comment sys/stat.h
1690 @comment GNU
1691 @deftypefun mode_t getumask (void)
1692 Return the current value of the file creation mask for the current
1693 process. This function is a GNU extension.
1694 @end deftypefun
1695
1696 @comment sys/stat.h
1697 @comment POSIX.1
1698 @deftypefun int chmod (const char *@var{filename}, mode_t @var{mode})
1699 The @code{chmod} function sets the access permission bits for the file
1700 named by @var{filename} to @var{mode}.
1701
1702 If the @var{filename} names a symbolic link, @code{chmod} changes the
1703 permission of the file pointed to by the link, not those of the link
1704 itself.
1705
1706 This function returns @code{0} if successful and @code{-1} if not. In
1707 addition to the usual file name errors (@pxref{File Name
1708 Errors}), the following @code{errno} error conditions are defined for
1709 this function:
1710
1711 @table @code
1712 @item ENOENT
1713 The named file doesn't exist.
1714
1715 @item EPERM
1716 This process does not have permission to change the access permission of
1717 this file. Only the file's owner (as judged by the effective user ID of
1718 the process) or a privileged user can change them.
1719
1720 @item EROFS
1721 The file resides on a read-only file system.
1722
1723 @item EFTYPE
1724 @var{mode} has the @code{S_ISVTX} bit (the ``sticky bit'') set,
1725 and the named file is not a directory. Some systems do not allow setting the
1726 sticky bit on non-directory files, and some do (and only some of those
1727 assign a useful meaning to the bit for non-directory files).
1728
1729 You only get @code{EFTYPE} on systems where the sticky bit has no useful
1730 meaning for non-directory files, so it is always safe to just clear the
1731 bit in @var{mode} and call @code{chmod} again. @xref{Permission Bits},
1732 for full details on the sticky bit.
1733 @end table
1734 @end deftypefun
1735
1736 @comment sys/stat.h
1737 @comment BSD
1738 @deftypefun int fchmod (int @var{filedes}, int @var{mode})
1739 This is like @code{chmod}, except that it changes the permissions of
1740 the file currently open via descriptor @var{filedes}.
1741
1742 The return value from @code{fchmod} is @code{0} on success and @code{-1}
1743 on failure. The following @code{errno} error codes are defined for this
1744 function:
1745
1746 @table @code
1747 @item EBADF
1748 The @var{filedes} argument is not a valid file descriptor.
1749
1750 @item EINVAL
1751 The @var{filedes} argument corresponds to a pipe or socket, or something
1752 else that doesn't really have access permissions.
1753
1754 @item EPERM
1755 This process does not have permission to change the access permission of
1756 this file. Only the file's owner (as judged by the effective user ID of
1757 the process) or a privileged user can change them.
1758
1759 @item EROFS
1760 The file resides on a read-only file system.
1761 @end table
1762 @end deftypefun
1763
1764 @node Testing File Access
1765 @subsection Testing Permission to Access a File
1766 @cindex testing access permission
1767 @cindex access, testing for
1768 @cindex setuid programs and file access
1769
1770 When a program runs as a privileged user, this permits it to access
1771 files off-limits to ordinary users---for example, to modify
1772 @file{/etc/passwd}. Programs designed to be run by ordinary users but
1773 access such files use the setuid bit feature so that they always run
1774 with @code{root} as the effective user ID.
1775
1776 Such a program may also access files specified by the user, files which
1777 conceptually are being accessed explicitly by the user. Since the
1778 program runs as @code{root}, it has permission to access whatever file
1779 the user specifies---but usually the desired behavior is to permit only
1780 those files which the user could ordinarily access.
1781
1782 The program therefore must explicitly check whether @emph{the user}
1783 would have the necessary access to a file, before it reads or writes the
1784 file.
1785
1786 To do this, use the function @code{access}, which checks for access
1787 permission based on the process's @emph{real} user ID rather than the
1788 effective user ID. (The setuid feature does not alter the real user ID,
1789 so it reflects the user who actually ran the program.)
1790
1791 There is another way you could check this access, which is easy to
1792 describe, but very hard to use. This is to examine the file mode bits
1793 and mimic the system's own access computation. This method is
1794 undesirable because many systems have additional access control
1795 features; your program cannot portably mimic them, and you would not
1796 want to try to keep track of the diverse features that different systems
1797 have. Using @code{access} is simple and automatically does whatever is
1798 appropriate for the system you are using.
1799
1800 @code{access} is @emph{only} only appropriate to use in setuid programs.
1801 A non-setuid program will always use the effective ID rather than the
1802 real ID.
1803
1804 @pindex unistd.h
1805 The symbols in this section are declared in @file{unistd.h}.
1806
1807 @comment unistd.h
1808 @comment POSIX.1
1809 @deftypefun int access (const char *@var{filename}, int @var{how})
1810 The @code{access} function checks to see whether the file named by
1811 @var{filename} can be accessed in the way specified by the @var{how}
1812 argument. The @var{how} argument either can be the bitwise OR of the
1813 flags @code{R_OK}, @code{W_OK}, @code{X_OK}, or the existence test
1814 @code{F_OK}.
1815
1816 This function uses the @emph{real} user and group ID's of the calling
1817 process, rather than the @emph{effective} ID's, to check for access
1818 permission. As a result, if you use the function from a @code{setuid}
1819 or @code{setgid} program (@pxref{How Change Persona}), it gives
1820 information relative to the user who actually ran the program.
1821
1822 The return value is @code{0} if the access is permitted, and @code{-1}
1823 otherwise. (In other words, treated as a predicate function,
1824 @code{access} returns true if the requested access is @emph{denied}.)
1825
1826 In addition to the usual file name errors (@pxref{File Name
1827 Errors}), the following @code{errno} error conditions are defined for
1828 this function:
1829
1830 @table @code
1831 @item EACCES
1832 The access specified by @var{how} is denied.
1833
1834 @item ENOENT
1835 The file doesn't exist.
1836
1837 @item EROFS
1838 Write permission was requested for a file on a read-only file system.
1839 @end table
1840 @end deftypefun
1841
1842 These macros are defined in the header file @file{unistd.h} for use
1843 as the @var{how} argument to the @code{access} function. The values
1844 are integer constants.
1845 @pindex unistd.h
1846
1847 @comment unistd.h
1848 @comment POSIX.1
1849 @deftypevr Macro int R_OK
1850 Argument that means, test for read permission.
1851 @end deftypevr
1852
1853 @comment unistd.h
1854 @comment POSIX.1
1855 @deftypevr Macro int W_OK
1856 Argument that means, test for write permission.
1857 @end deftypevr
1858
1859 @comment unistd.h
1860 @comment POSIX.1
1861 @deftypevr Macro int X_OK
1862 Argument that means, test for execute/search permission.
1863 @end deftypevr
1864
1865 @comment unistd.h
1866 @comment POSIX.1
1867 @deftypevr Macro int F_OK
1868 Argument that means, test for existence of the file.
1869 @end deftypevr
1870
1871 @node File Times
1872 @subsection File Times
1873
1874 @cindex file access time
1875 @cindex file modification time
1876 @cindex file attribute modification time
1877 Each file has three timestamps associated with it: its access time,
1878 its modification time, and its attribute modification time. These
1879 correspond to the @code{st_atime}, @code{st_mtime}, and @code{st_ctime}
1880 members of the @code{stat} structure; see @ref{File Attributes}.
1881
1882 All of these times are represented in calendar time format, as
1883 @code{time_t} objects. This data type is defined in @file{time.h}.
1884 For more information about representation and manipulation of time
1885 values, see @ref{Calendar Time}.
1886 @pindex time.h
1887
1888 Reading from a file updates its access time attribute, and writing
1889 updates its modification time. When a file is created, all three
1890 timestamps for that file are set to the current time. In addition, the
1891 attribute change time and modification time fields of the directory that
1892 contains the new entry are updated.
1893
1894 Adding a new name for a file with the @code{link} function updates the
1895 attribute change time field of the file being linked, and both the
1896 attribute change time and modification time fields of the directory
1897 containing the new name. These same fields are affected if a file name
1898 is deleted with @code{unlink}, @code{remove}, or @code{rmdir}. Renaming
1899 a file with @code{rename} affects only the attribute change time and
1900 modification time fields of the two parent directories involved, and not
1901 the times for the file being renamed.
1902
1903 Changing attributes of a file (for example, with @code{chmod}) updates
1904 its attribute change time field.
1905
1906 You can also change some of the timestamps of a file explicitly using
1907 the @code{utime} function---all except the attribute change time. You
1908 need to include the header file @file{utime.h} to use this facility.
1909 @pindex utime.h
1910
1911 @comment time.h
1912 @comment POSIX.1
1913 @deftp {Data Type} {struct utimbuf}
1914 The @code{utimbuf} structure is used with the @code{utime} function to
1915 specify new access and modification times for a file. It contains the
1916 following members:
1917
1918 @table @code
1919 @item time_t actime
1920 This is the access time for the file.
1921
1922 @item time_t modtime
1923 This is the modification time for the file.
1924 @end table
1925 @end deftp
1926
1927 @comment time.h
1928 @comment POSIX.1
1929 @deftypefun int utime (const char *@var{filename}, const struct utimbuf *@var{times})
1930 This function is used to modify the file times associated with the file
1931 named @var{filename}.
1932
1933 If @var{times} is a null pointer, then the access and modification times
1934 of the file are set to the current time. Otherwise, they are set to the
1935 values from the @code{actime} and @code{modtime} members (respectively)
1936 of the @code{utimbuf} structure pointed at by @var{times}.
1937
1938 The attribute modification time for the file is set to the current time
1939 in either case (since changing the timestamps is itself a modification
1940 of the file attributes).
1941
1942 The @code{utime} function returns @code{0} if successful and @code{-1}
1943 on failure. In addition to the usual file name errors
1944 (@pxref{File Name Errors}), the following @code{errno} error conditions
1945 are defined for this function:
1946
1947 @table @code
1948 @item EACCES
1949 There is a permission problem in the case where a null pointer was
1950 passed as the @var{times} argument. In order to update the timestamp on
1951 the file, you must either be the owner of the file, have write
1952 permission on the file, or be a privileged user.
1953
1954 @item ENOENT
1955 The file doesn't exist.
1956
1957 @item EPERM
1958 If the @var{times} argument is not a null pointer, you must either be
1959 the owner of the file or be a privileged user. This error is used to
1960 report the problem.
1961
1962 @item EROFS
1963 The file lives on a read-only file system.
1964 @end table
1965 @end deftypefun
1966
1967 Each of the three time stamps has a corresponding microsecond part,
1968 which extends its resolution. These fields are called
1969 @code{st_atime_usec}, @code{st_mtime_usec}, and @code{st_ctime_usec};
1970 each has a value between 0 and 999,999, which indicates the time in
1971 microseconds. They correspond to the @code{tv_usec} field of a
1972 @code{timeval} structure; see @ref{High-Resolution Calendar}.
1973
1974 The @code{utimes} function is like @code{utime}, but also lets you specify
1975 the fractional part of the file times. The prototype for this function is
1976 in the header file @file{sys/time.h}.
1977 @pindex sys/time.h
1978
1979 @comment sys/time.h
1980 @comment BSD
1981 @deftypefun int utimes (const char *@var{filename}, struct timeval @var{tvp}@t{[2]})
1982 This function sets the file access and modification times for the file
1983 named by @var{filename}. The new file access time is specified by
1984 @code{@var{tvp}[0]}, and the new modification time by
1985 @code{@var{tvp}[1]}. This function comes from BSD.
1986
1987 The return values and error conditions are the same as for the @code{utime}
1988 function.
1989 @end deftypefun
1990
1991 @node Making Special Files
1992 @section Making Special Files
1993 @cindex creating special files
1994 @cindex special files
1995
1996 The @code{mknod} function is the primitive for making special files,
1997 such as files that correspond to devices. The GNU library includes
1998 this function for compatibility with BSD.
1999
2000 The prototype for @code{mknod} is declared in @file{sys/stat.h}.
2001 @pindex sys/stat.h
2002
2003 @comment sys/stat.h
2004 @comment BSD
2005 @deftypefun int mknod (const char *@var{filename}, int @var{mode}, int @var{dev})
2006 The @code{mknod} function makes a special file with name @var{filename}.
2007 The @var{mode} specifies the mode of the file, and may include the various
2008 special file bits, such as @code{S_IFCHR} (for a character special file)
2009 or @code{S_IFBLK} (for a block special file). @xref{Testing File Type}.
2010
2011 The @var{dev} argument specifies which device the special file refers to.
2012 Its exact interpretation depends on the kind of special file being created.
2013
2014 The return value is @code{0} on success and @code{-1} on error. In addition
2015 to the usual file name errors (@pxref{File Name Errors}), the
2016 following @code{errno} error conditions are defined for this function:
2017
2018 @table @code
2019 @item EPERM
2020 The calling process is not privileged. Only the superuser can create
2021 special files.
2022
2023 @item ENOSPC
2024 The directory or file system that would contain the new file is full
2025 and cannot be extended.
2026
2027 @item EROFS
2028 The directory containing the new file can't be modified because it's on
2029 a read-only file system.
2030
2031 @item EEXIST
2032 There is already a file named @var{filename}. If you want to replace
2033 this file, you must remove the old file explicitly first.
2034 @end table
2035 @end deftypefun
2036
2037 @node Temporary Files
2038 @section Temporary Files
2039
2040 If you need to use a temporary file in your program, you can use the
2041 @code{tmpfile} function to open it. Or you can use the @code{tmpnam}
2042 (better: @code{tmpnam_r}) function make a name for a temporary file and
2043 then open it in the usual way with @code{fopen}.
2044
2045 The @code{tempnam} function is like @code{tmpnam} but lets you choose
2046 what directory temporary files will go in, and something about what
2047 their file names will look like. Important for multi threaded programs
2048 is that @code{tempnam} is reentrant while @code{tmpnam} is not since it
2049 returns a pointer to a static buffer.
2050
2051 These facilities are declared in the header file @file{stdio.h}.
2052 @pindex stdio.h
2053
2054 @comment stdio.h
2055 @comment ISO
2056 @deftypefun {FILE *} tmpfile (void)
2057 This function creates a temporary binary file for update mode, as if by
2058 calling @code{fopen} with mode @code{"wb+"}. The file is deleted
2059 automatically when it is closed or when the program terminates. (On
2060 some other @w{ISO C} systems the file may fail to be deleted if the program
2061 terminates abnormally).
2062
2063 This function is reentrant.
2064 @end deftypefun
2065
2066 @comment stdio.h
2067 @comment ISO
2068 @deftypefun {char *} tmpnam (char *@var{result})
2069 This function constructs and returns a file name that is a valid file
2070 name and that does not name any existing file. If the @var{result}
2071 argument is a null pointer, the return value is a pointer to an internal
2072 static string, which might be modified by subsequent calls and therefore
2073 makes this function non-reentrant. Otherwise, the @var{result} argument
2074 should be a pointer to an array of at least @code{L_tmpnam} characters,
2075 and the result is written into that array.
2076
2077 It is possible for @code{tmpnam} to fail if you call it too many times
2078 without removing previously created files. This is because the fixed
2079 length of a temporary file name gives room for only a finite number of
2080 different names. If @code{tmpnam} fails, it returns a null pointer.
2081 @end deftypefun
2082
2083 @comment stdio.h
2084 @comment GNU
2085 @deftypefun {char *} tmpnam_r (char *@var{result})
2086 This function is nearly identical to the @code{tmpnam} function. But it
2087 does not allow @var{result} to be a null pointer. In the later case a
2088 null pointer is returned.
2089
2090 This function is reentrant because the non-reentrant situation of
2091 @code{tmpnam} cannot happen here.
2092 @end deftypefun
2093
2094 @comment stdio.h
2095 @comment ISO
2096 @deftypevr Macro int L_tmpnam
2097 The value of this macro is an integer constant expression that represents
2098 the minimum allocation size of a string large enough to hold the
2099 file name generated by the @code{tmpnam} function.
2100 @end deftypevr
2101
2102 @comment stdio.h
2103 @comment ISO
2104 @deftypevr Macro int TMP_MAX
2105 The macro @code{TMP_MAX} is a lower bound for how many temporary names
2106 you can create with @code{tmpnam}. You can rely on being able to call
2107 @code{tmpnam} at least this many times before it might fail saying you
2108 have made too many temporary file names.
2109
2110 With the GNU library, you can create a very large number of temporary
2111 file names---if you actually create the files, you will probably run out
2112 of disk space before you run out of names. Some other systems have a
2113 fixed, small limit on the number of temporary files. The limit is never
2114 less than @code{25}.
2115 @end deftypevr
2116
2117 @comment stdio.h
2118 @comment SVID
2119 @deftypefun {char *} tempnam (const char *@var{dir}, const char *@var{prefix})
2120 This function generates a unique temporary filename. If @var{prefix} is
2121 not a null pointer, up to five characters of this string are used as a
2122 prefix for the file name. The return value is a string newly allocated
2123 with @code{malloc}; you should release its storage with @code{free} when
2124 it is no longer needed.
2125
2126 Because the string is dynamically allocated this function is reentrant.
2127
2128 The directory prefix for the temporary file name is determined by testing
2129 each of the following, in sequence. The directory must exist and be
2130 writable.
2131
2132 @itemize @bullet
2133 @item
2134 The environment variable @code{TMPDIR}, if it is defined. For security
2135 reasons this only happens if the program is not SUID or SGID enabled.
2136
2137 @item
2138 The @var{dir} argument, if it is not a null pointer.
2139
2140 @item
2141 The value of the @code{P_tmpdir} macro.
2142
2143 @item
2144 The directory @file{/tmp}.
2145 @end itemize
2146
2147 This function is defined for SVID compatibility.
2148 @end deftypefun
2149 @cindex TMPDIR environment variable
2150
2151 @comment stdio.h
2152 @comment SVID
2153 @c !!! are we putting SVID/GNU/POSIX.1/BSD in here or not??
2154 @deftypevr {SVID Macro} {char *} P_tmpdir
2155 This macro is the name of the default directory for temporary files.
2156 @end deftypevr
2157
2158 Older Unix systems did not have the functions just described. Instead
2159 they used @code{mktemp} and @code{mkstemp}. Both of these functions
2160 work by modifying a file name template string you pass. The last six
2161 characters of this string must be @samp{XXXXXX}. These six @samp{X}s
2162 are replaced with six characters which make the whole string a unique
2163 file name. Usually the template string is something like
2164 @samp{/tmp/@var{prefix}XXXXXX}, and each program uses a unique @var{prefix}.
2165
2166 @strong{Note:} Because @code{mktemp} and @code{mkstemp} modify the
2167 template string, you @emph{must not} pass string constants to them.
2168 String constants are normally in read-only storage, so your program
2169 would crash when @code{mktemp} or @code{mkstemp} tried to modify the
2170 string.
2171
2172 @comment unistd.h
2173 @comment Unix
2174 @deftypefun {char *} mktemp (char *@var{template})
2175 The @code{mktemp} function generates a unique file name by modifying
2176 @var{template} as described above. If successful, it returns
2177 @var{template} as modified. If @code{mktemp} cannot find a unique file
2178 name, it makes @var{template} an empty string and returns that. If
2179 @var{template} does not end with @samp{XXXXXX}, @code{mktemp} returns a
2180 null pointer.
2181 @end deftypefun
2182
2183 @comment unistd.h
2184 @comment BSD
2185 @deftypefun int mkstemp (char *@var{template})
2186 The @code{mkstemp} function generates a unique file name just as
2187 @code{mktemp} does, but it also opens the file for you with @code{open}
2188 (@pxref{Opening and Closing Files}). If successful, it modifies
2189 @var{template} in place and returns a file descriptor open on that file
2190 for reading and writing. If @code{mkstemp} cannot create a
2191 uniquely-named file, it makes @var{template} an empty string and returns
2192 @code{-1}. If @var{template} does not end with @samp{XXXXXX},
2193 @code{mkstemp} returns @code{-1} and does not modify @var{template}.
2194 @end deftypefun
2195
2196 Unlike @code{mktemp}, @code{mkstemp} is actually guaranteed to create a
2197 unique file that cannot possibly clash with any other program trying to
2198 create a temporary file. This is because it works by calling
2199 @code{open} with the @code{O_EXCL} flag bit, which says you want to
2200 always create a new file, and get an error if the file already exists.