Update.
[glibc.git] / manual / filesys.texi
blob3f62aa14a30583ac07b2b5c8f194fae1c54c34cc
1 @node File System Interface, Pipes and FIFOs, Low-Level I/O, Top
2 @c %MENU% Functions for manipulating files
3 @chapter File System Interface
5 This chapter describes the GNU C library's functions for manipulating
6 files.  Unlike the input and output functions (@pxref{I/O on Streams};
7 @pxref{Low-Level I/O}), these functions are concerned with operating
8 on the files themselves rather than on their contents.
10 Among the facilities described in this chapter are functions for
11 examining or modifying directories, functions for renaming and deleting
12 files, and functions for examining and setting file attributes such as
13 access permissions and modification times.
15 @menu
16 * Working Directory::           This is used to resolve relative
17                                  file names.
18 * Accessing Directories::       Finding out what files a directory
19                                  contains.
20 * Working with Directory Trees:: Apply actions to all files or a selectable
21                                  subset of a directory hierarchy.
22 * Hard Links::                  Adding alternate names to a file.
23 * Symbolic Links::              A file that ``points to'' a file name.
24 * Deleting Files::              How to delete a file, and what that means.
25 * Renaming Files::              Changing a file's name.
26 * Creating Directories::        A system call just for creating a directory.
27 * File Attributes::             Attributes of individual files.
28 * Making Special Files::        How to create special files.
29 * Temporary Files::             Naming and creating temporary files.
30 @end menu
32 @node Working Directory
33 @section Working Directory
35 @cindex current working directory
36 @cindex working directory
37 @cindex change working directory
38 Each process has associated with it a directory, called its @dfn{current
39 working directory} or simply @dfn{working directory}, that is used in
40 the resolution of relative file names (@pxref{File Name Resolution}).
42 When you log in and begin a new session, your working directory is
43 initially set to the home directory associated with your login account
44 in the system user database.  You can find any user's home directory
45 using the @code{getpwuid} or @code{getpwnam} functions; see @ref{User
46 Database}.
48 Users can change the working directory using shell commands like
49 @code{cd}.  The functions described in this section are the primitives
50 used by those commands and by other programs for examining and changing
51 the working directory.
52 @pindex cd
54 Prototypes for these functions are declared in the header file
55 @file{unistd.h}.
56 @pindex unistd.h
58 @comment unistd.h
59 @comment POSIX.1
60 @deftypefun {char *} getcwd (char *@var{buffer}, size_t @var{size})
61 The @code{getcwd} function returns an absolute file name representing
62 the current working directory, storing it in the character array
63 @var{buffer} that you provide.  The @var{size} argument is how you tell
64 the system the allocation size of @var{buffer}.
66 The GNU library version of this function also permits you to specify a
67 null pointer for the @var{buffer} argument.  Then @code{getcwd}
68 allocates a buffer automatically, as with @code{malloc}
69 (@pxref{Unconstrained Allocation}).  If the @var{size} is greater than
70 zero, then the buffer is that large; otherwise, the buffer is as large
71 as necessary to hold the result.
73 The return value is @var{buffer} on success and a null pointer on failure.
74 The following @code{errno} error conditions are defined for this function:
76 @table @code
77 @item EINVAL
78 The @var{size} argument is zero and @var{buffer} is not a null pointer.
80 @item ERANGE
81 The @var{size} argument is less than the length of the working directory
82 name.  You need to allocate a bigger array and try again.
84 @item EACCES
85 Permission to read or search a component of the file name was denied.
86 @end table
87 @end deftypefun
89 You could implement the behavior of GNU's @w{@code{getcwd (NULL, 0)}}
90 using only the standard behavior of @code{getcwd}:
92 @smallexample
93 char *
94 gnu_getcwd ()
96   size_t size = 100;
98   while (1)
99     @{
100       char *buffer = (char *) xmalloc (size);
101       if (getcwd (buffer, size) == buffer)
102         return buffer;
103       free (buffer);
104       if (errno != ERANGE)
105         return 0;
106       size *= 2;
107     @}
109 @end smallexample
111 @noindent
112 @xref{Malloc Examples}, for information about @code{xmalloc}, which is
113 not a library function but is a customary name used in most GNU
114 software.
116 @comment unistd.h
117 @comment BSD
118 @deftypefun {char *} getwd (char *@var{buffer})
119 This is similar to @code{getcwd}, but has no way to specify the size of
120 the buffer.  The GNU library provides @code{getwd} only
121 for backwards compatibility with BSD.
123 The @var{buffer} argument should be a pointer to an array at least
124 @code{PATH_MAX} bytes long (@pxref{Limits for Files}).  In the GNU
125 system there is no limit to the size of a file name, so this is not
126 necessarily enough space to contain the directory name.  That is why
127 this function is deprecated.
128 @end deftypefun
130 @comment unistd.h
131 @comment POSIX.1
132 @deftypefun int chdir (const char *@var{filename})
133 This function is used to set the process's working directory to
134 @var{filename}.
136 The normal, successful return value from @code{chdir} is @code{0}.  A
137 value of @code{-1} is returned to indicate an error.  The @code{errno}
138 error conditions defined for this function are the usual file name
139 syntax errors (@pxref{File Name Errors}), plus @code{ENOTDIR} if the
140 file @var{filename} is not a directory.
141 @end deftypefun
144 @node Accessing Directories
145 @section Accessing Directories
146 @cindex accessing directories
147 @cindex reading from a directory
148 @cindex directories, accessing
150 The facilities described in this section let you read the contents of a
151 directory file.  This is useful if you want your program to list all the
152 files in a directory, perhaps as part of a menu.
154 @cindex directory stream
155 The @code{opendir} function opens a @dfn{directory stream} whose
156 elements are directory entries.  You use the @code{readdir} function on
157 the directory stream to retrieve these entries, represented as
158 @w{@code{struct dirent}} objects.  The name of the file for each entry is
159 stored in the @code{d_name} member of this structure.  There are obvious
160 parallels here to the stream facilities for ordinary files, described in
161 @ref{I/O on Streams}.
163 @menu
164 * Directory Entries::           Format of one directory entry.
165 * Opening a Directory::         How to open a directory stream.
166 * Reading/Closing Directory::   How to read directory entries from the stream.
167 * Simple Directory Lister::     A very simple directory listing program.
168 * Random Access Directory::     Rereading part of the directory
169                                  already read with the same stream.
170 * Scanning Directory Content::  Get entries for user selected subset of
171                                  contents in given directory.
172 * Simple Directory Lister Mark II::  Revised version of the program.
173 @end menu
175 @node Directory Entries
176 @subsection Format of a Directory Entry
178 @pindex dirent.h
179 This section describes what you find in a single directory entry, as you
180 might obtain it from a directory stream.  All the symbols are declared
181 in the header file @file{dirent.h}.
183 @comment dirent.h
184 @comment POSIX.1
185 @deftp {Data Type} {struct dirent}
186 This is a structure type used to return information about directory
187 entries.  It contains the following fields:
189 @table @code
190 @item char d_name[]
191 This is the null-terminated file name component.  This is the only
192 field you can count on in all POSIX systems.
194 @item ino_t d_fileno
195 This is the file serial number.  For BSD compatibility, you can also
196 refer to this member as @code{d_ino}.  In the GNU system and most POSIX
197 systems, for most files this the same as the @code{st_ino} member that
198 @code{stat} will return for the file.  @xref{File Attributes}.
200 @item unsigned char d_namlen
201 This is the length of the file name, not including the terminating null
202 character.  Its type is @code{unsigned char} because that is the integer
203 type of the appropriate size
205 @item unsigned char d_type
206 This is the type of the file, possibly unknown.  The following constants
207 are defined for its value:
209 @table @code
210 @item DT_UNKNOWN
211 The type is unknown.  On some systems this is the only value returned.
213 @item DT_REG
214 A regular file.
216 @item DT_DIR
217 A directory.
219 @item DT_FIFO
220 A named pipe, or FIFO.  @xref{FIFO Special Files}.
222 @item DT_SOCK
223 A local-domain socket.  @c !!! @xref{Local Domain}.
225 @item DT_CHR
226 A character device.
228 @item DT_BLK
229 A block device.
230 @end table
232 This member is a BSD extension.  On systems where it is used, it
233 corresponds to the file type bits in the @code{st_mode} member of
234 @code{struct statbuf}.  On other systems it will always be DT_UNKNOWN.
235 These two macros convert between @code{d_type} values and @code{st_mode}
236 values:
238 @deftypefun int IFTODT (mode_t @var{mode})
239 This returns the @code{d_type} value corresponding to @var{mode}.
240 @end deftypefun
242 @deftypefun mode_t DTTOIF (int @var{dtype})
243 This returns the @code{st_mode} value corresponding to @var{dtype}.
244 @end deftypefun
245 @end table
247 This structure may contain additional members in the future.
249 When a file has multiple names, each name has its own directory entry.
250 The only way you can tell that the directory entries belong to a
251 single file is that they have the same value for the @code{d_fileno}
252 field.
254 File attributes such as size, modification times etc., are part of the
255 file itself, not of any particular directory entry.  @xref{File
256 Attributes}.
257 @end deftp
259 @node Opening a Directory
260 @subsection Opening a Directory Stream
262 @pindex dirent.h
263 This section describes how to open a directory stream.  All the symbols
264 are declared in the header file @file{dirent.h}.
266 @comment dirent.h
267 @comment POSIX.1
268 @deftp {Data Type} DIR
269 The @code{DIR} data type represents a directory stream.
270 @end deftp
272 You shouldn't ever allocate objects of the @code{struct dirent} or
273 @code{DIR} data types, since the directory access functions do that for
274 you.  Instead, you refer to these objects using the pointers returned by
275 the following functions.
277 @comment dirent.h
278 @comment POSIX.1
279 @deftypefun {DIR *} opendir (const char *@var{dirname})
280 The @code{opendir} function opens and returns a directory stream for
281 reading the directory whose file name is @var{dirname}.  The stream has
282 type @code{DIR *}.
284 If unsuccessful, @code{opendir} returns a null pointer.  In addition to
285 the usual file name errors (@pxref{File Name Errors}), the
286 following @code{errno} error conditions are defined for this function:
288 @table @code
289 @item EACCES
290 Read permission is denied for the directory named by @code{dirname}.
292 @item EMFILE
293 The process has too many files open.
295 @item ENFILE
296 The entire system, or perhaps the file system which contains the
297 directory, cannot support any additional open files at the moment.
298 (This problem cannot happen on the GNU system.)
299 @end table
301 The @code{DIR} type is typically implemented using a file descriptor,
302 and the @code{opendir} function in terms of the @code{open} function.
303 @xref{Low-Level I/O}.  Directory streams and the underlying
304 file descriptors are closed on @code{exec} (@pxref{Executing a File}).
305 @end deftypefun
307 @node Reading/Closing Directory
308 @subsection Reading and Closing a Directory Stream
310 @pindex dirent.h
311 This section describes how to read directory entries from a directory
312 stream, and how to close the stream when you are done with it.  All the
313 symbols are declared in the header file @file{dirent.h}.
315 @comment dirent.h
316 @comment POSIX.1
317 @deftypefun {struct dirent *} readdir (DIR *@var{dirstream})
318 This function reads the next entry from the directory.  It normally
319 returns a pointer to a structure containing information about the file.
320 This structure is statically allocated and can be rewritten by a
321 subsequent call.
323 @strong{Portability Note:} On some systems @code{readdir} may not
324 return entries for @file{.} and @file{..}, even though these are always
325 valid file names in any directory.  @xref{File Name Resolution}.
327 If there are no more entries in the directory or an error is detected,
328 @code{readdir} returns a null pointer.  The following @code{errno} error
329 conditions are defined for this function:
331 @table @code
332 @item EBADF
333 The @var{dirstream} argument is not valid.
334 @end table
336 @code{readdir} is not thread safe.  Multiple threads using
337 @code{readdir} on the same @var{dirstream} may overwrite the return
338 value.  Use @code{readdir_r} when this is critical.
339 @end deftypefun
341 @comment dirent.h
342 @comment GNU
343 @deftypefun int readdir_r (DIR *@var{dirstream}, struct dirent *@var{entry}, struct dirent **@var{result})
344 This function is the reentrant version of @code{readdir}.  Like
345 @code{readdir} it returns the next entry from the directory.  But to
346 prevent conflicts between simultaneously running threads the result is
347 not stored in statically allocated memory.  Instead the argument
348 @var{entry} points to a place to store the result.
350 The return value is @code{0} in case the next entry was read
351 successfully.  In this case a pointer to the result is returned in
352 *@var{result}.  It is not required that *@var{result} is the same as
353 @var{entry}.  If something goes wrong while executing @code{readdir_r}
354 the function returns a value indicating the error (as described for
355 @code{readdir}).
357 If there are no more directory entries, @code{readdir_r}'s return value is
358 @code{0}, and *@var{result} is set to @code{NULL}.
360 @strong{Portability Note:} On some systems @code{readdir_r} may not
361 return a NUL terminated string for the file name, even when there is no
362 @code{d_reclen} field in @code{struct dirent} and the file
363 name is the maximum allowed size.  Modern systems all have the
364 @code{d_reclen} field, and on old systems multi-threading is not
365 critical.  In any case there is no such problem with the @code{readdir}
366 function, so that even on systems without the @code{d_reclen} member one
367 could use multiple threads by using external locking.
368 @end deftypefun
370 @comment dirent.h
371 @comment POSIX.1
372 @deftypefun int closedir (DIR *@var{dirstream})
373 This function closes the directory stream @var{dirstream}.  It returns
374 @code{0} on success and @code{-1} on failure.
376 The following @code{errno} error conditions are defined for this
377 function:
379 @table @code
380 @item EBADF
381 The @var{dirstream} argument is not valid.
382 @end table
383 @end deftypefun
385 @node Simple Directory Lister
386 @subsection Simple Program to List a Directory
388 Here's a simple program that prints the names of the files in
389 the current working directory:
391 @smallexample
392 @include dir.c.texi
393 @end smallexample
395 The order in which files appear in a directory tends to be fairly
396 random.  A more useful program would sort the entries (perhaps by
397 alphabetizing them) before printing them; see
398 @ref{Scanning Directory Content}, and @ref{Array Sort Function}.
401 @node Random Access Directory
402 @subsection Random Access in a Directory Stream
404 @pindex dirent.h
405 This section describes how to reread parts of a directory that you have
406 already read from an open directory stream.  All the symbols are
407 declared in the header file @file{dirent.h}.
409 @comment dirent.h
410 @comment POSIX.1
411 @deftypefun void rewinddir (DIR *@var{dirstream})
412 The @code{rewinddir} function is used to reinitialize the directory
413 stream @var{dirstream}, so that if you call @code{readdir} it
414 returns information about the first entry in the directory again.  This
415 function also notices if files have been added or removed to the
416 directory since it was opened with @code{opendir}.  (Entries for these
417 files might or might not be returned by @code{readdir} if they were
418 added or removed since you last called @code{opendir} or
419 @code{rewinddir}.)
420 @end deftypefun
422 @comment dirent.h
423 @comment BSD
424 @deftypefun off_t telldir (DIR *@var{dirstream})
425 The @code{telldir} function returns the file position of the directory
426 stream @var{dirstream}.  You can use this value with @code{seekdir} to
427 restore the directory stream to that position.
428 @end deftypefun
430 @comment dirent.h
431 @comment BSD
432 @deftypefun void seekdir (DIR *@var{dirstream}, off_t @var{pos})
433 The @code{seekdir} function sets the file position of the directory
434 stream @var{dirstream} to @var{pos}.  The value @var{pos} must be the
435 result of a previous call to @code{telldir} on this particular stream;
436 closing and reopening the directory can invalidate values returned by
437 @code{telldir}.
438 @end deftypefun
441 @node Scanning Directory Content
442 @subsection Scanning the Content of a Directory
444 A higher-level interface to the directory handling functions is the
445 @code{scandir} function.  With its help one can select a subset of the
446 entries in a directory, possibly sort them and get a list of names as
447 the result.
449 @comment dirent.h
450 @comment BSD/SVID
451 @deftypefun int scandir (const char *@var{dir}, struct dirent ***@var{namelist}, int (*@var{selector}) (const struct dirent *), int (*@var{cmp}) (const void *, const void *))
453 The @code{scandir} function scans the contents of the directory selected
454 by @var{dir}.  The result in *@var{namelist} is an array of pointers to
455 structure of type @code{struct dirent} which describe all selected
456 directory entries and which is allocated using @code{malloc}.  Instead
457 of always getting all directory entries returned, the user supplied
458 function @var{selector} can be used to decide which entries are in the
459 result.  Only the entries for which @var{selector} returns a non-zero
460 value are selected.
462 Finally the entries in *@var{namelist} are sorted using the
463 user-supplied function @var{cmp}.  The arguments passed to the @var{cmp}
464 function are of type @code{struct dirent **}, therefore one cannot
465 directly use the @code{strcmp} or @code{strcoll} functions; instead see
466 the functions @code{alphasort} and @code{versionsort} below.
468 The return value of the function is the number of entries placed in
469 *@var{namelist}.  If it is @code{-1} an error occurred (either the
470 directory could not be opened for reading or the malloc call failed) and
471 the global variable @code{errno} contains more information on the error.
472 @end deftypefun
474 As described above the fourth argument to the @code{scandir} function
475 must be a pointer to a sorting function.  For the convenience of the
476 programmer the GNU C library contains implementations of functions which
477 are very helpful for this purpose.
479 @comment dirent.h
480 @comment BSD/SVID
481 @deftypefun int alphasort (const void *@var{a}, const void *@var{b})
482 The @code{alphasort} function behaves like the @code{strcoll} function
483 (@pxref{String/Array Comparison}).  The difference is that the arguments
484 are not string pointers but instead they are of type
485 @code{struct dirent **}.
487 The return value of @code{alphasort} is less than, equal to, or greater
488 than zero depending on the order of the two entries @var{a} and @var{b}.
489 @end deftypefun
491 @comment dirent.h
492 @comment GNU
493 @deftypefun int versionsort (const void *@var{a}, const void *@var{b})
494 The @code{versionsort} function is like @code{alphasort} except that it
495 uses the @code{strverscmp} function internally.
496 @end deftypefun
498 If the filesystem supports large files we cannot use the @code{scandir}
499 anymore since the @code{dirent} structure might not able to contain all
500 the information.  The LFS provides the new type @w{@code{struct
501 dirent64}}.  To use this we need a new function.
503 @comment dirent.h
504 @comment GNU
505 @deftypefun int scandir64 (const char *@var{dir}, struct dirent64 ***@var{namelist}, int (*@var{selector}) (const struct dirent64 *), int (*@var{cmp}) (const void *, const void *))
506 The @code{scandir64} function works like the @code{scandir} function
507 except that the directory entries it returns are described by elements
508 of type @w{@code{struct dirent64}}.  The function pointed to by
509 @var{selector} is again used to select the desired entries, except that
510 @var{selector} now must point to a function which takes a
511 @w{@code{struct dirent64 *}} parameter.
513 Similarly the @var{cmp} function should expect its two arguments to be
514 of type @code{struct dirent64 **}.
515 @end deftypefun
517 As @var{cmp} is now a function of a different type, the functions
518 @code{alphasort} and @code{versionsort} cannot be supplied for that
519 argument.  Instead we provide the two replacement functions below.
521 @comment dirent.h
522 @comment GNU
523 @deftypefun int alphasort64 (const void *@var{a}, const void *@var{b})
524 The @code{alphasort64} function behaves like the @code{strcoll} function
525 (@pxref{String/Array Comparison}).  The difference is that the arguments
526 are not string pointers but instead they are of type
527 @code{struct dirent64 **}.
529 Return value of @code{alphasort64} is less than, equal to, or greater
530 than zero depending on the order of the two entries @var{a} and @var{b}.
531 @end deftypefun
533 @comment dirent.h
534 @comment GNU
535 @deftypefun int versionsort64 (const void *@var{a}, const void *@var{b})
536 The @code{versionsort64} function is like @code{alphasort64}, excepted that it
537 uses the @code{strverscmp} function internally.
538 @end deftypefun
540 It is important not to mix the use of @code{scandir} and the 64-bit
541 comparison functions or vice versa.  There are systems on which this
542 works but on others it will fail miserably.
544 @node Simple Directory Lister Mark II
545 @subsection Simple Program to List a Directory, Mark II
547 Here is a revised version of the directory lister found above
548 (@pxref{Simple Directory Lister}).  Using the @code{scandir} function we
549 can avoid the functions which work directly with the directory contents.
550 After the call the returned entries are available for direct use.
552 @smallexample
553 @include dir2.c.texi
554 @end smallexample
556 Note the simple selector function in this example.  Since we want to see
557 all directory entries we always return @code{1}.
560 @node Working with Directory Trees
561 @section Working with Directory Trees
562 @cindex directory hierarchy
563 @cindex hierarchy, directory
564 @cindex tree, directory
566 The functions described so far for handling the files in a directory
567 have allowed you to either retrieve the information bit by bit, or to
568 process all the files as a group (see @code{scandir}).  Sometimes it is
569 useful to process whole hierarchies of directories and their contained
570 files.  The X/Open specification defines two functions to do this.  The
571 simpler form is derived from an early definition in @w{System V} systems
572 and therefore this function is available on SVID-derived systems.  The
573 prototypes and required definitions can be found in the @file{ftw.h}
574 header.
576 There are four functions in this family: @code{ftw}, @code{nftw} and
577 their 64-bit counterparts @code{ftw64} and @code{nftw64}.  These
578 functions take as one of their arguments a pointer to a callback
579 function of the appropriate type.
581 @comment ftw.h
582 @comment GNU
583 @deftp {Data Type} __ftw_func_t
585 @smallexample
586 int (*) (const char *, const struct stat *, int)
587 @end smallexample
589 The type of callback functions given to the @code{ftw} function.  The
590 first parameter points to the file name, the second parameter to an
591 object of type @code{struct stat} which is filled in for the file named
592 in the first parameter.
594 @noindent
595 The last parameter is a flag giving more information about the current
596 file.  It can have the following values:
598 @vtable @code
599 @item FTW_F
600 The item is either a normal file or a file which does not fit into one
601 of the following categories.  This could be special files, sockets etc.
602 @item FTW_D
603 The item is a directory.
604 @item FTW_NS
605 The @code{stat} call failed and so the information pointed to by the
606 second paramater is invalid.
607 @item FTW_DNR
608 The item is a directory which cannot be read.
609 @item FTW_SL
610 The item is a symbolic link.  Since symbolic links are normally followed
611 seeing this value in a @code{ftw} callback function means the referenced
612 file does not exist.  The situation for @code{nftw} is different.
614 This value is only available if the program is compiled with
615 @code{_BSD_SOURCE} or @code{_XOPEN_EXTENDED} defined before including
616 the first header.  The original SVID systems do not have symbolic links.
617 @end vtable
619 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
620 type is in fact @code{__ftw64_func_t} since this mode changes
621 @code{struct stat} to be @code{struct stat64}.
622 @end deftp
624 For the LFS interface and for use in the function @code{ftw64}, the
625 header @file{ftw.h} defines another function type.
627 @comment ftw.h
628 @comment GNU
629 @deftp {Data Type} __ftw64_func_t
631 @smallexample
632 int (*) (const char *, const struct stat64 *, int)
633 @end smallexample
635 This type is used just like @code{__ftw_func_t} for the callback
636 function, but this time is called from @code{ftw64}.  The second
637 parameter to the function is a pointer to a variable of type
638 @code{struct stat64} which is able to represent the larger values.
639 @end deftp
641 @comment ftw.h
642 @comment GNU
643 @deftp {Data Type} __nftw_func_t
645 @smallexample
646 int (*) (const char *, const struct stat *, int, struct FTW *)
647 @end smallexample
649 @vindex FTW_DP
650 @vindex FTW_SLN
651 The first three arguments are the same as for the @code{__ftw_func_t}
652 type.  However for the third argument some additional values are defined
653 to allow finer differentiation:
654 @table @code
655 @item FTW_DP
656 The current item is a directory and all subdirectories have already been
657 visited and reported.  This flag is returned instead of @code{FTW_D} if
658 the @code{FTW_DEPTH} flag is passed to @code{nftw} (see below).
659 @item FTW_SLN
660 The current item is a stale symbolic link.  The file it points to does
661 not exist.
662 @end table
664 The last parameter of the callback function is a pointer to a structure
665 with some extra information as described below.
667 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
668 type is in fact @code{__nftw64_func_t} since this mode changes
669 @code{struct stat} to be @code{struct stat64}.
670 @end deftp
672 For the LFS interface there is also a variant of this data type
673 available which has to be used with the @code{nftw64} function.
675 @comment ftw.h
676 @comment GNU
677 @deftp {Data Type} __nftw64_func_t
679 @smallexample
680 int (*) (const char *, const struct stat64 *, int, struct FTW *)
681 @end smallexample
683 This type is used just like @code{__nftw_func_t} for the callback
684 function, but this time is called from @code{nftw64}.  The second
685 parameter to the function is this time a pointer to a variable of type
686 @code{struct stat64} which is able to represent the larger values.
687 @end deftp
689 @comment ftw.h
690 @comment XPG4.2
691 @deftp {Data Type} {struct FTW}
692 The information contained in this structure helps in interpreting the
693 name parameter and gives some information about the current state of the
694 traversal of the directory hierarchy.
696 @table @code
697 @item int base
698 The value is the offset into the string passed in the first parameter to
699 the callback function of the beginning of the file name.  The rest of
700 the string is the path of the file.  This information is especially
701 important if the @code{FTW_CHDIR} flag was set in calling @code{nftw}
702 since then the current directory is the one the current item is found
704 @item int level
705 Whilst processing, the code tracks how many directories down it has gone
706 to find the current file.  This nesting level starts at @math{0} for
707 files in the initial directory (or is zero for the initial file if a
708 file was passed).
709 @end table
710 @end deftp
713 @comment ftw.h
714 @comment SVID
715 @deftypefun int ftw (const char *@var{filename}, __ftw_func_t @var{func}, int @var{descriptors})
716 The @code{ftw} function calls the callback function given in the
717 parameter @var{func} for every item which is found in the directory
718 specified by @var{filename} and all directories below.  The function
719 follows symbolic links if necessary but does not process an item twice.
720 If @var{filename} is not a directory then it itself is the only object
721 returned to the callback function.
723 The file name passed to the callback function is constructed by taking
724 the @var{filename} parameter and appending the names of all passed
725 directories and then the local file name.  So the callback function can
726 use this parameter to access the file.  @code{ftw} also calls
727 @code{stat} for the file and passes that information on to the callback
728 function.  If this @code{stat} call was not successful the failure is
729 indicated by setting the third argument of the callback function to
730 @code{FTW_NS}.  Otherwise it is set according to the description given
731 in the account of @code{__ftw_func_t} above.
733 The callback function is expected to return @math{0} to indicate that no
734 error occurred and that processing should continue.  If an error
735 occurred in the callback function or it wants @code{ftw} to return
736 immediately, the callback function can return a value other than
737 @math{0}.  This is the only correct way to stop the function.  The
738 program must not use @code{setjmp} or similar techniques to continue
739 from another place.  This would leave resources allocated by the
740 @code{ftw} function unfreed.
742 The @var{descriptors} parameter to @code{ftw} specifies how many file
743 descriptors it is allowed to consume.  The function runs faster the more
744 descriptors it can use.  For each level in the directory hierarchy at
745 most one descriptor is used, but for very deep ones any limit on open
746 file descriptors for the process or the system may be exceeded.
747 Moreover, file descriptor limits in a multi-threaded program apply to
748 all the threads as a group, and therefore it is a good idea to supply a
749 reasonable limit to the number of open descriptors.
751 The return value of the @code{ftw} function is @math{0} if all callback
752 function calls returned @math{0} and all actions performed by the
753 @code{ftw} succeeded.  If a function call failed (other than calling
754 @code{stat} on an item) the function returns @math{-1}.  If a callback
755 function returns a value other than @math{0} this value is returned as
756 the return value of @code{ftw}.
758 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
759 32-bit system this function is in fact @code{ftw64}, i.e. the LFS
760 interface transparently replaces the old interface.
761 @end deftypefun
763 @comment ftw.h
764 @comment Unix98
765 @deftypefun int ftw64 (const char *@var{filename}, __ftw64_func_t @var{func}, int @var{descriptors})
766 This function is similar to @code{ftw} but it can work on filesystems
767 with large files.  File information is reported using a variable of type
768 @code{struct stat64} which is passed by reference to the callback
769 function.
771 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
772 32-bit system this function is available under the name @code{ftw} and
773 transparently replaces the old implementation.
774 @end deftypefun
776 @comment ftw.h
777 @comment XPG4.2
778 @deftypefun int nftw (const char *@var{filename}, __nftw_func_t @var{func}, int @var{descriptors}, int @var{flag})
779 The @code{nftw} function works like the @code{ftw} functions.  They call
780 the callback function @var{func} for all items found in the directory
781 @var{filename} and below.  At most @var{descriptors} file descriptors
782 are consumed during the @code{nftw} call.
784 One difference is that the callback function is of a different type.  It
785 is of type @w{@code{struct FTW *}} and provides the callback function
786 with the extra information described above.
788 A second difference is that @code{nftw} takes a fourth argument, which
789 is @math{0} or a bitwise-OR combination of any of the following values.
791 @vtable @code
792 @item FTW_PHYS
793 While traversing the directory symbolic links are not followed.  Instead
794 symbolic links are reported using the @code{FTW_SL} value for the type
795 parameter to the callback function.  If the file referenced by a
796 symbolic link does not exist @code{FTW_SLN} is returned instead.
797 @item FTW_MOUNT
798 The callback function is only called for items which are on the same
799 mounted filesystem as the directory given by the @var{filename}
800 parameter to @code{nftw}.
801 @item FTW_CHDIR
802 If this flag is given the current working directory is changed to the
803 directory of the reported object before the callback function is called.
804 When @code{ntfw} finally returns the current directory is restored to
805 its original value.
806 @item FTW_DEPTH
807 If this option is specified then all subdirectories and files within
808 them are processed before processing the top directory itself
809 (depth-first processing).  This also means the type flag given to the
810 callback function is @code{FTW_DP} and not @code{FTW_D}.
811 @end vtable
813 The return value is computed in the same way as for @code{ftw}.
814 @code{nftw} returns @math{0} if no failures occurred and all callback
815 functions returned @math{0}.  In case of internal errors, such as memory
816 problems, the return value is @math{-1} and @var{errno} is set
817 accordingly.  If the return value of a callback invocation was non-zero
818 then that value is returned.
820 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
821 32-bit system this function is in fact @code{nftw64}, i.e. the LFS
822 interface transparently replaces the old interface.
823 @end deftypefun
825 @comment ftw.h
826 @comment Unix98
827 @deftypefun int nftw64 (const char *@var{filename}, __nftw64_func_t @var{func}, int @var{descriptors}, int @var{flag})
828 This function is similar to @code{nftw} but it can work on filesystems
829 with large files.  File information is reported using a variable of type
830 @code{struct stat64} which is passed by reference to the callback
831 function.
833 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
834 32-bit system this function is available under the name @code{nftw} and
835 transparently replaces the old implementation.
836 @end deftypefun
839 @node Hard Links
840 @section Hard Links
841 @cindex hard link
842 @cindex link, hard
843 @cindex multiple names for one file
844 @cindex file names, multiple
846 In POSIX systems, one file can have many names at the same time.  All of
847 the names are equally real, and no one of them is preferred to the
848 others.
850 To add a name to a file, use the @code{link} function.  (The new name is
851 also called a @dfn{hard link} to the file.)  Creating a new link to a
852 file does not copy the contents of the file; it simply makes a new name
853 by which the file can be known, in addition to the file's existing name
854 or names.
856 One file can have names in several directories, so the organization
857 of the file system is not a strict hierarchy or tree.
859 In most implementations, it is not possible to have hard links to the
860 same file in multiple file systems.  @code{link} reports an error if you
861 try to make a hard link to the file from another file system when this
862 cannot be done.
864 The prototype for the @code{link} function is declared in the header
865 file @file{unistd.h}.
866 @pindex unistd.h
868 @comment unistd.h
869 @comment POSIX.1
870 @deftypefun int link (const char *@var{oldname}, const char *@var{newname})
871 The @code{link} function makes a new link to the existing file named by
872 @var{oldname}, under the new name @var{newname}.
874 This function returns a value of @code{0} if it is successful and
875 @code{-1} on failure.  In addition to the usual file name errors
876 (@pxref{File Name Errors}) for both @var{oldname} and @var{newname}, the
877 following @code{errno} error conditions are defined for this function:
879 @table @code
880 @item EACCES
881 You are not allowed to write to the directory in which the new link is
882 to be written.
883 @ignore
884 Some implementations also require that the existing file be accessible
885 by the caller, and use this error to report failure for that reason.
886 @end ignore
888 @item EEXIST
889 There is already a file named @var{newname}.  If you want to replace
890 this link with a new link, you must remove the old link explicitly first.
892 @item EMLINK
893 There are already too many links to the file named by @var{oldname}.
894 (The maximum number of links to a file is @w{@code{LINK_MAX}}; see
895 @ref{Limits for Files}.)
897 @item ENOENT
898 The file named by @var{oldname} doesn't exist.  You can't make a link to
899 a file that doesn't exist.
901 @item ENOSPC
902 The directory or file system that would contain the new link is full
903 and cannot be extended.
905 @item EPERM
906 In the GNU system and some others, you cannot make links to directories.
907 Many systems allow only privileged users to do so.  This error
908 is used to report the problem.
910 @item EROFS
911 The directory containing the new link can't be modified because it's on
912 a read-only file system.
914 @item EXDEV
915 The directory specified in @var{newname} is on a different file system
916 than the existing file.
918 @item EIO
919 A hardware error occurred while trying to read or write the to filesystem.
920 @end table
921 @end deftypefun
923 @node Symbolic Links
924 @section Symbolic Links
925 @cindex soft link
926 @cindex link, soft
927 @cindex symbolic link
928 @cindex link, symbolic
930 The GNU system supports @dfn{soft links} or @dfn{symbolic links}.  This
931 is a kind of ``file'' that is essentially a pointer to another file
932 name.  Unlike hard links, symbolic links can be made to directories or
933 across file systems with no restrictions.  You can also make a symbolic
934 link to a name which is not the name of any file.  (Opening this link
935 will fail until a file by that name is created.)  Likewise, if the
936 symbolic link points to an existing file which is later deleted, the
937 symbolic link continues to point to the same file name even though the
938 name no longer names any file.
940 The reason symbolic links work the way they do is that special things
941 happen when you try to open the link.  The @code{open} function realizes
942 you have specified the name of a link, reads the file name contained in
943 the link, and opens that file name instead.  The @code{stat} function
944 likewise operates on the file that the symbolic link points to, instead
945 of on the link itself.
947 By contrast, other operations such as deleting or renaming the file
948 operate on the link itself.  The functions @code{readlink} and
949 @code{lstat} also refrain from following symbolic links, because their
950 purpose is to obtain information about the link.  @code{link}, the
951 function that makes a hard link, does too.  It makes a hard link to the
952 symbolic link, which one rarely wants.
954 Prototypes for the functions listed in this section are in
955 @file{unistd.h}.
956 @pindex unistd.h
958 @comment unistd.h
959 @comment BSD
960 @deftypefun int symlink (const char *@var{oldname}, const char *@var{newname})
961 The @code{symlink} function makes a symbolic link to @var{oldname} named
962 @var{newname}.
964 The normal return value from @code{symlink} is @code{0}.  A return value
965 of @code{-1} indicates an error.  In addition to the usual file name
966 syntax errors (@pxref{File Name Errors}), the following @code{errno}
967 error conditions are defined for this function:
969 @table @code
970 @item EEXIST
971 There is already an existing file named @var{newname}.
973 @item EROFS
974 The file @var{newname} would exist on a read-only file system.
976 @item ENOSPC
977 The directory or file system cannot be extended to make the new link.
979 @item EIO
980 A hardware error occurred while reading or writing data on the disk.
982 @ignore
983 @comment not sure about these
984 @item ELOOP
985 There are too many levels of indirection.  This can be the result of
986 circular symbolic links to directories.
988 @item EDQUOT
989 The new link can't be created because the user's disk quota has been
990 exceeded.
991 @end ignore
992 @end table
993 @end deftypefun
995 @comment unistd.h
996 @comment BSD
997 @deftypefun int readlink (const char *@var{filename}, char *@var{buffer}, size_t @var{size})
998 The @code{readlink} function gets the value of the symbolic link
999 @var{filename}.  The file name that the link points to is copied into
1000 @var{buffer}.  This file name string is @emph{not} null-terminated;
1001 @code{readlink} normally returns the number of characters copied.  The
1002 @var{size} argument specifies the maximum number of characters to copy,
1003 usually the allocation size of @var{buffer}.
1005 If the return value equals @var{size}, you cannot tell whether or not
1006 there was room to return the entire name.  So make a bigger buffer and
1007 call @code{readlink} again.  Here is an example:
1009 @smallexample
1010 char *
1011 readlink_malloc (char *filename)
1013   int size = 100;
1015   while (1)
1016     @{
1017       char *buffer = (char *) xmalloc (size);
1018       int nchars = readlink (filename, buffer, size);
1019       if (nchars < size)
1020         return buffer;
1021       free (buffer);
1022       size *= 2;
1023     @}
1025 @end smallexample
1027 @c @group  Invalid outside example.
1028 A value of @code{-1} is returned in case of error.  In addition to the
1029 usual file name errors (@pxref{File Name Errors}), the following
1030 @code{errno} error conditions are defined for this function:
1032 @table @code
1033 @item EINVAL
1034 The named file is not a symbolic link.
1036 @item EIO
1037 A hardware error occurred while reading or writing data on the disk.
1038 @end table
1039 @c @end group
1040 @end deftypefun
1042 @node Deleting Files
1043 @section Deleting Files
1044 @cindex deleting a file
1045 @cindex removing a file
1046 @cindex unlinking a file
1048 You can delete a file with @code{unlink} or @code{remove}.
1050 Deletion actually deletes a file name.  If this is the file's only name,
1051 then the file is deleted as well.  If the file has other remaining names
1052 (@pxref{Hard Links}), it remains accessible under those names.
1054 @comment unistd.h
1055 @comment POSIX.1
1056 @deftypefun int unlink (const char *@var{filename})
1057 The @code{unlink} function deletes the file name @var{filename}.  If
1058 this is a file's sole name, the file itself is also deleted.  (Actually,
1059 if any process has the file open when this happens, deletion is
1060 postponed until all processes have closed the file.)
1062 @pindex unistd.h
1063 The function @code{unlink} is declared in the header file @file{unistd.h}.
1065 This function returns @code{0} on successful completion, and @code{-1}
1066 on error.  In addition to the usual file name errors
1067 (@pxref{File Name Errors}), the following @code{errno} error conditions are
1068 defined for this function:
1070 @table @code
1071 @item EACCES
1072 Write permission is denied for the directory from which the file is to be
1073 removed, or the directory has the sticky bit set and you do not own the file.
1075 @item EBUSY
1076 This error indicates that the file is being used by the system in such a
1077 way that it can't be unlinked.  For example, you might see this error if
1078 the file name specifies the root directory or a mount point for a file
1079 system.
1081 @item ENOENT
1082 The file name to be deleted doesn't exist.
1084 @item EPERM
1085 On some systems @code{unlink} cannot be used to delete the name of a
1086 directory, or at least can only be used this way by a privileged user.
1087 To avoid such problems, use @code{rmdir} to delete directories.  (In the
1088 GNU system @code{unlink} can never delete the name of a directory.)
1090 @item EROFS
1091 The directory containing the file name to be deleted is on a read-only
1092 file system and can't be modified.
1093 @end table
1094 @end deftypefun
1096 @comment unistd.h
1097 @comment POSIX.1
1098 @deftypefun int rmdir (const char *@var{filename})
1099 @cindex directories, deleting
1100 @cindex deleting a directory
1101 The @code{rmdir} function deletes a directory.  The directory must be
1102 empty before it can be removed; in other words, it can only contain
1103 entries for @file{.} and @file{..}.
1105 In most other respects, @code{rmdir} behaves like @code{unlink}.  There
1106 are two additional @code{errno} error conditions defined for
1107 @code{rmdir}:
1109 @table @code
1110 @item ENOTEMPTY
1111 @itemx EEXIST
1112 The directory to be deleted is not empty.
1113 @end table
1115 These two error codes are synonymous; some systems use one, and some use
1116 the other.  The GNU system always uses @code{ENOTEMPTY}.
1118 The prototype for this function is declared in the header file
1119 @file{unistd.h}.
1120 @pindex unistd.h
1121 @end deftypefun
1123 @comment stdio.h
1124 @comment ISO
1125 @deftypefun int remove (const char *@var{filename})
1126 This is the @w{ISO C} function to remove a file.  It works like
1127 @code{unlink} for files and like @code{rmdir} for directories.
1128 @code{remove} is declared in @file{stdio.h}.
1129 @pindex stdio.h
1130 @end deftypefun
1132 @node Renaming Files
1133 @section Renaming Files
1135 The @code{rename} function is used to change a file's name.
1137 @cindex renaming a file
1138 @comment stdio.h
1139 @comment ISO
1140 @deftypefun int rename (const char *@var{oldname}, const char *@var{newname})
1141 The @code{rename} function renames the file @var{oldname} to
1142 @var{newname}.  The file formerly accessible under the name
1143 @var{oldname} is afterwards accessible as @var{newname} instead.  (If
1144 the file had any other names aside from @var{oldname}, it continues to
1145 have those names.)
1147 The directory containing the name @var{newname} must be on the same file
1148 system as the directory containing the name @var{oldname}.
1150 One special case for @code{rename} is when @var{oldname} and
1151 @var{newname} are two names for the same file.  The consistent way to
1152 handle this case is to delete @var{oldname}.  However, in this case
1153 POSIX requires that @code{rename} do nothing and report success---which
1154 is inconsistent.  We don't know what your operating system will do.
1156 If @var{oldname} is not a directory, then any existing file named
1157 @var{newname} is removed during the renaming operation.  However, if
1158 @var{newname} is the name of a directory, @code{rename} fails in this
1159 case.
1161 If @var{oldname} is a directory, then either @var{newname} must not
1162 exist or it must name a directory that is empty.  In the latter case,
1163 the existing directory named @var{newname} is deleted first.  The name
1164 @var{newname} must not specify a subdirectory of the directory
1165 @code{oldname} which is being renamed.
1167 One useful feature of @code{rename} is that the meaning of @var{newname}
1168 changes ``atomically'' from any previously existing file by that name to
1169 its new meaning (i.e. the file that was called @var{oldname}).  There is
1170 no instant at which @var{newname} is non-existent ``in between'' the old
1171 meaning and the new meaning.  If there is a system crash during the
1172 operation, it is possible for both names to still exist; but
1173 @var{newname} will always be intact if it exists at all.
1175 If @code{rename} fails, it returns @code{-1}.  In addition to the usual
1176 file name errors (@pxref{File Name Errors}), the following
1177 @code{errno} error conditions are defined for this function:
1179 @table @code
1180 @item EACCES
1181 One of the directories containing @var{newname} or @var{oldname}
1182 refuses write permission; or @var{newname} and @var{oldname} are
1183 directories and write permission is refused for one of them.
1185 @item EBUSY
1186 A directory named by @var{oldname} or @var{newname} is being used by
1187 the system in a way that prevents the renaming from working.  This includes
1188 directories that are mount points for filesystems, and directories
1189 that are the current working directories of processes.
1191 @item ENOTEMPTY
1192 @itemx EEXIST
1193 The directory @var{newname} isn't empty.  The GNU system always returns
1194 @code{ENOTEMPTY} for this, but some other systems return @code{EEXIST}.
1196 @item EINVAL
1197 @var{oldname} is a directory that contains @var{newname}.
1199 @item EISDIR
1200 @var{newname} is a directory but the @var{oldname} isn't.
1202 @item EMLINK
1203 The parent directory of @var{newname} would have too many links
1204 (entries).
1206 @item ENOENT
1207 The file @var{oldname} doesn't exist.
1209 @item ENOSPC
1210 The directory that would contain @var{newname} has no room for another
1211 entry, and there is no space left in the file system to expand it.
1213 @item EROFS
1214 The operation would involve writing to a directory on a read-only file
1215 system.
1217 @item EXDEV
1218 The two file names @var{newname} and @var{oldname} are on different
1219 file systems.
1220 @end table
1221 @end deftypefun
1223 @node Creating Directories
1224 @section Creating Directories
1225 @cindex creating a directory
1226 @cindex directories, creating
1228 @pindex mkdir
1229 Directories are created with the @code{mkdir} function.  (There is also
1230 a shell command @code{mkdir} which does the same thing.)
1231 @c !!! umask
1233 @comment sys/stat.h
1234 @comment POSIX.1
1235 @deftypefun int mkdir (const char *@var{filename}, mode_t @var{mode})
1236 The @code{mkdir} function creates a new, empty directory with name
1237 @var{filename}.
1239 The argument @var{mode} specifies the file permissions for the new
1240 directory file.  @xref{Permission Bits}, for more information about
1241 this.
1243 A return value of @code{0} indicates successful completion, and
1244 @code{-1} indicates failure.  In addition to the usual file name syntax
1245 errors (@pxref{File Name Errors}), the following @code{errno} error
1246 conditions are defined for this function:
1248 @table @code
1249 @item EACCES
1250 Write permission is denied for the parent directory in which the new
1251 directory is to be added.
1253 @item EEXIST
1254 A file named @var{filename} already exists.
1256 @item EMLINK
1257 The parent directory has too many links (entries).
1259 Well-designed file systems never report this error, because they permit
1260 more links than your disk could possibly hold.  However, you must still
1261 take account of the possibility of this error, as it could result from
1262 network access to a file system on another machine.
1264 @item ENOSPC
1265 The file system doesn't have enough room to create the new directory.
1267 @item EROFS
1268 The parent directory of the directory being created is on a read-only
1269 file system and cannot be modified.
1270 @end table
1272 To use this function, your program should include the header file
1273 @file{sys/stat.h}.
1274 @pindex sys/stat.h
1275 @end deftypefun
1277 @node File Attributes
1278 @section File Attributes
1280 @pindex ls
1281 When you issue an @samp{ls -l} shell command on a file, it gives you
1282 information about the size of the file, who owns it, when it was last
1283 modified, etc.  These are called the @dfn{file attributes}, and are
1284 associated with the file itself and not a particular one of its names.
1286 This section contains information about how you can inquire about and
1287 modify the attributes of a file.
1289 @menu
1290 * Attribute Meanings::          The names of the file attributes,
1291                                  and what their values mean.
1292 * Reading Attributes::          How to read the attributes of a file.
1293 * Testing File Type::           Distinguishing ordinary files,
1294                                  directories, links...
1295 * File Owner::                  How ownership for new files is determined,
1296                                  and how to change it.
1297 * Permission Bits::             How information about a file's access
1298                                  mode is stored.
1299 * Access Permission::           How the system decides who can access a file.
1300 * Setting Permissions::         How permissions for new files are assigned,
1301                                  and how to change them.
1302 * Testing File Access::         How to find out if your process can
1303                                  access a file.
1304 * File Times::                  About the time attributes of a file.
1305 * File Size::                   Manually changing the size of a file.
1306 @end menu
1308 @node Attribute Meanings
1309 @subsection The meaning of the File Attributes
1310 @cindex status of a file
1311 @cindex attributes of a file
1312 @cindex file attributes
1314 When you read the attributes of a file, they come back in a structure
1315 called @code{struct stat}.  This section describes the names of the
1316 attributes, their data types, and what they mean.  For the functions
1317 to read the attributes of a file, see @ref{Reading Attributes}.
1319 The header file @file{sys/stat.h} declares all the symbols defined
1320 in this section.
1321 @pindex sys/stat.h
1323 @comment sys/stat.h
1324 @comment POSIX.1
1325 @deftp {Data Type} {struct stat}
1326 The @code{stat} structure type is used to return information about the
1327 attributes of a file.  It contains at least the following members:
1329 @table @code
1330 @item mode_t st_mode
1331 Specifies the mode of the file.  This includes file type information
1332 (@pxref{Testing File Type}) and the file permission bits
1333 (@pxref{Permission Bits}).
1335 @item ino_t st_ino
1336 The file serial number, which distinguishes this file from all other
1337 files on the same device.
1339 @item dev_t st_dev
1340 Identifies the device containing the file.  The @code{st_ino} and
1341 @code{st_dev}, taken together, uniquely identify the file.  The
1342 @code{st_dev} value is not necessarily consistent across reboots or
1343 system crashes, however.
1345 @item nlink_t st_nlink
1346 The number of hard links to the file.  This count keeps track of how
1347 many directories have entries for this file.  If the count is ever
1348 decremented to zero, then the file itself is discarded as soon as no
1349 process still holds it open.  Symbolic links are not counted in the
1350 total.
1352 @item uid_t st_uid
1353 The user ID of the file's owner.  @xref{File Owner}.
1355 @item gid_t st_gid
1356 The group ID of the file.  @xref{File Owner}.
1358 @item off_t st_size
1359 This specifies the size of a regular file in bytes.  For files that are
1360 really devices this field isn't usually meaningful.  For symbolic links
1361 this specifies the length of the file name the link refers to.
1363 @item time_t st_atime
1364 This is the last access time for the file.  @xref{File Times}.
1366 @item unsigned long int st_atime_usec
1367 This is the fractional part of the last access time for the file.
1368 @xref{File Times}.
1370 @item time_t st_mtime
1371 This is the time of the last modification to the contents of the file.
1372 @xref{File Times}.
1374 @item unsigned long int st_mtime_usec
1375 This is the fractional part of the time of the last modification to the
1376 contents of the file.  @xref{File Times}.
1378 @item time_t st_ctime
1379 This is the time of the last modification to the attributes of the file.
1380 @xref{File Times}.
1382 @item unsigned long int st_ctime_usec
1383 This is the fractional part of the time of the last modification to the
1384 attributes of the file.  @xref{File Times}.
1386 @c !!! st_rdev
1387 @item blkcnt_t st_blocks
1388 This is the amount of disk space that the file occupies, measured in
1389 units of 512-byte blocks.
1391 The number of disk blocks is not strictly proportional to the size of
1392 the file, for two reasons: the file system may use some blocks for
1393 internal record keeping; and the file may be sparse---it may have
1394 ``holes'' which contain zeros but do not actually take up space on the
1395 disk.
1397 You can tell (approximately) whether a file is sparse by comparing this
1398 value with @code{st_size}, like this:
1400 @smallexample
1401 (st.st_blocks * 512 < st.st_size)
1402 @end smallexample
1404 This test is not perfect because a file that is just slightly sparse
1405 might not be detected as sparse at all.  For practical applications,
1406 this is not a problem.
1408 @item unsigned int st_blksize
1409 The optimal block size for reading of writing this file, in bytes.  You
1410 might use this size for allocating the buffer space for reading of
1411 writing the file.  (This is unrelated to @code{st_blocks}.)
1412 @end table
1413 @end deftp
1415 The extensions for the Large File Support (LFS) require, even on 32-bit
1416 machines, types which can handle file sizes up to @math{2^63}.
1417 Therefore a new definition of @code{struct stat} is necessary.
1419 @comment sys/stat.h
1420 @comment LFS
1421 @deftp {Data Type} {struct stat64}
1422 The members of this type are the same and have the same names as those
1423 in @code{struct stat}.  The only difference is that the members
1424 @code{st_ino}, @code{st_size}, and @code{st_blocks} have a different
1425 type to support larger values.
1427 @table @code
1428 @item mode_t st_mode
1429 Specifies the mode of the file.  This includes file type information
1430 (@pxref{Testing File Type}) and the file permission bits
1431 (@pxref{Permission Bits}).
1433 @item ino64_t st_ino
1434 The file serial number, which distinguishes this file from all other
1435 files on the same device.
1437 @item dev_t st_dev
1438 Identifies the device containing the file.  The @code{st_ino} and
1439 @code{st_dev}, taken together, uniquely identify the file.  The
1440 @code{st_dev} value is not necessarily consistent across reboots or
1441 system crashes, however.
1443 @item nlink_t st_nlink
1444 The number of hard links to the file.  This count keeps track of how
1445 many directories have entries for this file.  If the count is ever
1446 decremented to zero, then the file itself is discarded as soon as no
1447 process still holds it open.  Symbolic links are not counted in the
1448 total.
1450 @item uid_t st_uid
1451 The user ID of the file's owner.  @xref{File Owner}.
1453 @item gid_t st_gid
1454 The group ID of the file.  @xref{File Owner}.
1456 @item off64_t st_size
1457 This specifies the size of a regular file in bytes.  For files that are
1458 really devices this field isn't usually meaningful.  For symbolic links
1459 this specifies the length of the file name the link refers to.
1461 @item time_t st_atime
1462 This is the last access time for the file.  @xref{File Times}.
1464 @item unsigned long int st_atime_usec
1465 This is the fractional part of the last access time for the file.
1466 @xref{File Times}.
1468 @item time_t st_mtime
1469 This is the time of the last modification to the contents of the file.
1470 @xref{File Times}.
1472 @item unsigned long int st_mtime_usec
1473 This is the fractional part of the time of the last modification to the
1474 contents of the file.  @xref{File Times}.
1476 @item time_t st_ctime
1477 This is the time of the last modification to the attributes of the file.
1478 @xref{File Times}.
1480 @item unsigned long int st_ctime_usec
1481 This is the fractional part of the time of the last modification to the
1482 attributes of the file.  @xref{File Times}.
1484 @c !!! st_rdev
1485 @item blkcnt64_t st_blocks
1486 This is the amount of disk space that the file occupies, measured in
1487 units of 512-byte blocks.
1489 @item unsigned int st_blksize
1490 The optimal block size for reading of writing this file, in bytes.  You
1491 might use this size for allocating the buffer space for reading of
1492 writing the file.  (This is unrelated to @code{st_blocks}.)
1493 @end table
1494 @end deftp
1496 Some of the file attributes have special data type names which exist
1497 specifically for those attributes.  (They are all aliases for well-known
1498 integer types that you know and love.)  These typedef names are defined
1499 in the header file @file{sys/types.h} as well as in @file{sys/stat.h}.
1500 Here is a list of them.
1502 @comment sys/types.h
1503 @comment POSIX.1
1504 @deftp {Data Type} mode_t
1505 This is an integer data type used to represent file modes.  In the
1506 GNU system, this is equivalent to @code{unsigned int}.
1507 @end deftp
1509 @cindex inode number
1510 @comment sys/types.h
1511 @comment POSIX.1
1512 @deftp {Data Type} ino_t
1513 This is an arithmetic data type used to represent file serial numbers.
1514 (In Unix jargon, these are sometimes called @dfn{inode numbers}.)
1515 In the GNU system, this type is equivalent to @code{unsigned long int}.
1517 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1518 is transparently replaced by @code{ino64_t}.
1519 @end deftp
1521 @comment sys/types.h
1522 @comment Unix98
1523 @deftp {Data Type} ino64_t
1524 This is an arithmetic data type used to represent file serial numbers
1525 for the use in LFS.  In the GNU system, this type is equivalent to
1526 @code{unsigned long longint}.
1528 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1529 available under the name @code{ino_t}.
1530 @end deftp
1532 @comment sys/types.h
1533 @comment POSIX.1
1534 @deftp {Data Type} dev_t
1535 This is an arithmetic data type used to represent file device numbers.
1536 In the GNU system, this is equivalent to @code{int}.
1537 @end deftp
1539 @comment sys/types.h
1540 @comment POSIX.1
1541 @deftp {Data Type} nlink_t
1542 This is an arithmetic data type used to represent file link counts.
1543 In the GNU system, this is equivalent to @code{unsigned short int}.
1544 @end deftp
1546 @comment sys/types.h
1547 @comment Unix98
1548 @deftp {Data Type} blkcnt_t
1549 This is an arithmetic data type used to represent block counts.
1550 In the GNU system, this is equivalent to @code{unsigned long int}.
1552 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
1553 is transparently replaced by @code{blkcnt64_t}.
1554 @end deftp
1556 @comment sys/types.h
1557 @comment Unix98
1558 @deftp {Data Type} blkcnt64_t
1559 This is an arithmetic data type used to represent block counts for the
1560 use in LFS.  In the GNU system, this is equivalent to @code{unsigned
1561 long long int}.
1563 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
1564 available under the name @code{blkcnt_t}.
1565 @end deftp
1567 @node Reading Attributes
1568 @subsection Reading the Attributes of a File
1570 To examine the attributes of files, use the functions @code{stat},
1571 @code{fstat} and @code{lstat}.  They return the attribute information in
1572 a @code{struct stat} object.  All three functions are declared in the
1573 header file @file{sys/stat.h}.
1575 @comment sys/stat.h
1576 @comment POSIX.1
1577 @deftypefun int stat (const char *@var{filename}, struct stat *@var{buf})
1578 The @code{stat} function returns information about the attributes of the
1579 file named by @w{@var{filename}} in the structure pointed to by @var{buf}.
1581 If @var{filename} is the name of a symbolic link, the attributes you get
1582 describe the file that the link points to.  If the link points to a
1583 nonexistent file name, then @code{stat} fails reporting a nonexistent
1584 file.
1586 The return value is @code{0} if the operation is successful, or
1587 @code{-1} on failure.  In addition to the usual file name errors
1588 (@pxref{File Name Errors}, the following @code{errno} error conditions
1589 are defined for this function:
1591 @table @code
1592 @item ENOENT
1593 The file named by @var{filename} doesn't exist.
1594 @end table
1596 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1597 function is in fact @code{stat64} since the LFS interface transparently
1598 replaces the normal implementation.
1599 @end deftypefun
1601 @comment sys/stat.h
1602 @comment Unix98
1603 @deftypefun int stat64 (const char *@var{filename}, struct stat64 *@var{buf})
1604 This function is similar to @code{stat} but it is also able to work on
1605 files larger then @math{2^31} bytes on 32-bit systems.  To be able to do
1606 this the result is stored in a variable of type @code{struct stat64} to
1607 which @var{buf} must point.
1609 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1610 function is available under the name @code{stat} and so transparently
1611 replaces the interface for small files on 32-bit machines.
1612 @end deftypefun
1614 @comment sys/stat.h
1615 @comment POSIX.1
1616 @deftypefun int fstat (int @var{filedes}, struct stat *@var{buf})
1617 The @code{fstat} function is like @code{stat}, except that it takes an
1618 open file descriptor as an argument instead of a file name.
1619 @xref{Low-Level I/O}.
1621 Like @code{stat}, @code{fstat} returns @code{0} on success and @code{-1}
1622 on failure.  The following @code{errno} error conditions are defined for
1623 @code{fstat}:
1625 @table @code
1626 @item EBADF
1627 The @var{filedes} argument is not a valid file descriptor.
1628 @end table
1630 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1631 function is in fact @code{fstat64} since the LFS interface transparently
1632 replaces the normal implementation.
1633 @end deftypefun
1635 @comment sys/stat.h
1636 @comment Unix98
1637 @deftypefun int fstat64 (int @var{filedes}, struct stat64 *@var{buf})
1638 This function is similar to @code{fstat} but is able to work on large
1639 files on 32-bit platforms.  For large files the file descriptor
1640 @var{filedes} should be obtained by @code{open64} or @code{creat64}.
1641 The @var{buf} pointer points to a variable of type @code{struct stat64}
1642 which is able to represent the larger values.
1644 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1645 function is available under the name @code{fstat} and so transparently
1646 replaces the interface for small files on 32-bit machines.
1647 @end deftypefun
1649 @comment sys/stat.h
1650 @comment BSD
1651 @deftypefun int lstat (const char *@var{filename}, struct stat *@var{buf})
1652 The @code{lstat} function is like @code{stat}, except that it does not
1653 follow symbolic links.  If @var{filename} is the name of a symbolic
1654 link, @code{lstat} returns information about the link itself; otherwise
1655 @code{lstat} works like @code{stat}.  @xref{Symbolic Links}.
1657 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1658 function is in fact @code{lstat64} since the LFS interface transparently
1659 replaces the normal implementation.
1660 @end deftypefun
1662 @comment sys/stat.h
1663 @comment Unix98
1664 @deftypefun int lstat64 (const char *@var{filename}, struct stat64 *@var{buf})
1665 This function is similar to @code{lstat} but it is also able to work on
1666 files larger then @math{2^31} bytes on 32-bit systems.  To be able to do
1667 this the result is stored in a variable of type @code{struct stat64} to
1668 which @var{buf} must point.
1670 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1671 function is available under the name @code{lstat} and so transparently
1672 replaces the interface for small files on 32-bit machines.
1673 @end deftypefun
1675 @node Testing File Type
1676 @subsection Testing the Type of a File
1678 The @dfn{file mode}, stored in the @code{st_mode} field of the file
1679 attributes, contains two kinds of information: the file type code, and
1680 the access permission bits.  This section discusses only the type code,
1681 which you can use to tell whether the file is a directory, socket,
1682 symbolic link, and so on.  For details about access permissions see
1683 @ref{Permission Bits}.
1685 There are two ways you can access the file type information in a file
1686 mode.  Firstly, for each file type there is a @dfn{predicate macro}
1687 which examines a given file mode and returns whether it is of that type
1688 or not.  Secondly, you can mask out the rest of the file mode to leave
1689 just the file type code, and compare this against constants for each of
1690 the supported file types.
1692 All of the symbols listed in this section are defined in the header file
1693 @file{sys/stat.h}.
1694 @pindex sys/stat.h
1696 The following predicate macros test the type of a file, given the value
1697 @var{m} which is the @code{st_mode} field returned by @code{stat} on
1698 that file:
1700 @comment sys/stat.h
1701 @comment POSIX
1702 @deftypefn Macro int S_ISDIR (mode_t @var{m})
1703 This macro returns non-zero if the file is a directory.
1704 @end deftypefn
1706 @comment sys/stat.h
1707 @comment POSIX
1708 @deftypefn Macro int S_ISCHR (mode_t @var{m})
1709 This macro returns non-zero if the file is a character special file (a
1710 device like a terminal).
1711 @end deftypefn
1713 @comment sys/stat.h
1714 @comment POSIX
1715 @deftypefn Macro int S_ISBLK (mode_t @var{m})
1716 This macro returns non-zero if the file is a block special file (a device
1717 like a disk).
1718 @end deftypefn
1720 @comment sys/stat.h
1721 @comment POSIX
1722 @deftypefn Macro int S_ISREG (mode_t @var{m})
1723 This macro returns non-zero if the file is a regular file.
1724 @end deftypefn
1726 @comment sys/stat.h
1727 @comment POSIX
1728 @deftypefn Macro int S_ISFIFO (mode_t @var{m})
1729 This macro returns non-zero if the file is a FIFO special file, or a
1730 pipe.  @xref{Pipes and FIFOs}.
1731 @end deftypefn
1733 @comment sys/stat.h
1734 @comment GNU
1735 @deftypefn Macro int S_ISLNK (mode_t @var{m})
1736 This macro returns non-zero if the file is a symbolic link.
1737 @xref{Symbolic Links}.
1738 @end deftypefn
1740 @comment sys/stat.h
1741 @comment GNU
1742 @deftypefn Macro int S_ISSOCK (mode_t @var{m})
1743 This macro returns non-zero if the file is a socket.  @xref{Sockets}.
1744 @end deftypefn
1746 An alternate non-POSIX method of testing the file type is supported for
1747 compatibility with BSD.  The mode can be bitwise AND-ed with
1748 @code{S_IFMT} to extract the file type code, and compared to the
1749 appropriate constant.  For example,
1751 @smallexample
1752 S_ISCHR (@var{mode})
1753 @end smallexample
1755 @noindent
1756 is equivalent to:
1758 @smallexample
1759 ((@var{mode} & S_IFMT) == S_IFCHR)
1760 @end smallexample
1762 @comment sys/stat.h
1763 @comment BSD
1764 @deftypevr Macro int S_IFMT
1765 This is a bit mask used to extract the file type code from a mode value.
1766 @end deftypevr
1768 These are the symbolic names for the different file type codes:
1770 @table @code
1771 @comment sys/stat.h
1772 @comment BSD
1773 @item S_IFDIR
1774 @vindex S_IFDIR
1775 This is the file type constant of a directory file.
1777 @comment sys/stat.h
1778 @comment BSD
1779 @item S_IFCHR
1780 @vindex S_IFCHR
1781 This is the file type constant of a character-oriented device file.
1783 @comment sys/stat.h
1784 @comment BSD
1785 @item S_IFBLK
1786 @vindex S_IFBLK
1787 This is the file type constant of a block-oriented device file.
1789 @comment sys/stat.h
1790 @comment BSD
1791 @item S_IFREG
1792 @vindex S_IFREG
1793 This is the file type constant of a regular file.
1795 @comment sys/stat.h
1796 @comment BSD
1797 @item S_IFLNK
1798 @vindex S_IFLNK
1799 This is the file type constant of a symbolic link.
1801 @comment sys/stat.h
1802 @comment BSD
1803 @item S_IFSOCK
1804 @vindex S_IFSOCK
1805 This is the file type constant of a socket.
1807 @comment sys/stat.h
1808 @comment BSD
1809 @item S_IFIFO
1810 @vindex S_IFIFO
1811 This is the file type constant of a FIFO or pipe.
1812 @end table
1814 The POSIX.1b standard introduced a few more objects which possibly can
1815 be implemented as object in the filesystem.  These are message queues,
1816 semaphores, and shared memory objects.  To allow differentiating these
1817 objects from other files the POSIX standard introduces three new test
1818 macros.  But unlike the other macros it does not take the value of the
1819 @code{st_mode} field as the parameter.  Instead they expect a pointer to
1820 the whole @code{struct stat} structure.
1822 @comment sys/stat.h
1823 @comment POSIX
1824 @deftypefn Macro int S_TYPEISMQ (struct stat @var{s})
1825 If the system implement POSIX message queues as distinct objects and the
1826 file is a message queue object, this macro returns a non-zero value.
1827 In all other cases the result is zero.
1828 @end deftypefn
1830 @comment sys/stat.h
1831 @comment POSIX
1832 @deftypefn Macro int S_TYPEISSEM (struct stat @var{s})
1833 If the system implement POSIX semaphores as distinct objects and the
1834 file is a semaphore object, this macro returns a non-zero value.
1835 In all other cases the result is zero.
1836 @end deftypefn
1838 @comment sys/stat.h
1839 @comment POSIX
1840 @deftypefn Macro int S_TYPEISSHM (struct stat @var{s})
1841 If the system implement POSIX shared memory objects as distinct objects
1842 and the file is an shared memory object, this macro returns a non-zero
1843 value.  In all other cases the result is zero.
1844 @end deftypefn
1846 @node File Owner
1847 @subsection File Owner
1848 @cindex file owner
1849 @cindex owner of a file
1850 @cindex group owner of a file
1852 Every file has an @dfn{owner} which is one of the registered user names
1853 defined on the system.  Each file also has a @dfn{group} which is one of
1854 the defined groups.  The file owner can often be useful for showing you
1855 who edited the file (especially when you edit with GNU Emacs), but its
1856 main purpose is for access control.
1858 The file owner and group play a role in determining access because the
1859 file has one set of access permission bits for the owner, another set
1860 that applies to users who belong to the file's group, and a third set of
1861 bits that applies to everyone else.  @xref{Access Permission}, for the
1862 details of how access is decided based on this data.
1864 When a file is created, its owner is set to the effective user ID of the
1865 process that creates it (@pxref{Process Persona}).  The file's group ID
1866 may be set to either the effective group ID of the process, or the group
1867 ID of the directory that contains the file, depending on the system
1868 where the file is stored.  When you access a remote file system, it
1869 behaves according to its own rules, not according to the system your
1870 program is running on.  Thus, your program must be prepared to encounter
1871 either kind of behavior no matter what kind of system you run it on.
1873 @pindex chown
1874 @pindex chgrp
1875 You can change the owner and/or group owner of an existing file using
1876 the @code{chown} function.  This is the primitive for the @code{chown}
1877 and @code{chgrp} shell commands.
1879 @pindex unistd.h
1880 The prototype for this function is declared in @file{unistd.h}.
1882 @comment unistd.h
1883 @comment POSIX.1
1884 @deftypefun int chown (const char *@var{filename}, uid_t @var{owner}, gid_t @var{group})
1885 The @code{chown} function changes the owner of the file @var{filename} to
1886 @var{owner}, and its group owner to @var{group}.
1888 Changing the owner of the file on certain systems clears the set-user-ID
1889 and set-group-ID permission bits.  (This is because those bits may not
1890 be appropriate for the new owner.)  Other file permission bits are not
1891 changed.
1893 The return value is @code{0} on success and @code{-1} on failure.
1894 In addition to the usual file name errors (@pxref{File Name Errors}),
1895 the following @code{errno} error conditions are defined for this function:
1897 @table @code
1898 @item EPERM
1899 This process lacks permission to make the requested change.
1901 Only privileged users or the file's owner can change the file's group.
1902 On most file systems, only privileged users can change the file owner;
1903 some file systems allow you to change the owner if you are currently the
1904 owner.  When you access a remote file system, the behavior you encounter
1905 is determined by the system that actually holds the file, not by the
1906 system your program is running on.
1908 @xref{Options for Files}, for information about the
1909 @code{_POSIX_CHOWN_RESTRICTED} macro.
1911 @item EROFS
1912 The file is on a read-only file system.
1913 @end table
1914 @end deftypefun
1916 @comment unistd.h
1917 @comment BSD
1918 @deftypefun int fchown (int @var{filedes}, int @var{owner}, int @var{group})
1919 This is like @code{chown}, except that it changes the owner of the open
1920 file with descriptor @var{filedes}.
1922 The return value from @code{fchown} is @code{0} on success and @code{-1}
1923 on failure.  The following @code{errno} error codes are defined for this
1924 function:
1926 @table @code
1927 @item EBADF
1928 The @var{filedes} argument is not a valid file descriptor.
1930 @item EINVAL
1931 The @var{filedes} argument corresponds to a pipe or socket, not an ordinary
1932 file.
1934 @item EPERM
1935 This process lacks permission to make the requested change.  For details
1936 see @code{chmod} above.
1938 @item EROFS
1939 The file resides on a read-only file system.
1940 @end table
1941 @end deftypefun
1943 @node Permission Bits
1944 @subsection The Mode Bits for Access Permission
1946 The @dfn{file mode}, stored in the @code{st_mode} field of the file
1947 attributes, contains two kinds of information: the file type code, and
1948 the access permission bits.  This section discusses only the access
1949 permission bits, which control who can read or write the file.
1950 @xref{Testing File Type}, for information about the file type code.
1952 All of the symbols listed in this section are defined in the header file
1953 @file{sys/stat.h}.
1954 @pindex sys/stat.h
1956 @cindex file permission bits
1957 These symbolic constants are defined for the file mode bits that control
1958 access permission for the file:
1960 @table @code
1961 @comment sys/stat.h
1962 @comment POSIX.1
1963 @item S_IRUSR
1964 @vindex S_IRUSR
1965 @comment sys/stat.h
1966 @comment BSD
1967 @itemx S_IREAD
1968 @vindex S_IREAD
1969 Read permission bit for the owner of the file.  On many systems this bit
1970 is 0400.  @code{S_IREAD} is an obsolete synonym provided for BSD
1971 compatibility.
1973 @comment sys/stat.h
1974 @comment POSIX.1
1975 @item S_IWUSR
1976 @vindex S_IWUSR
1977 @comment sys/stat.h
1978 @comment BSD
1979 @itemx S_IWRITE
1980 @vindex S_IWRITE
1981 Write permission bit for the owner of the file.  Usually 0200.
1982 @w{@code{S_IWRITE}} is an obsolete synonym provided for BSD compatibility.
1984 @comment sys/stat.h
1985 @comment POSIX.1
1986 @item S_IXUSR
1987 @vindex S_IXUSR
1988 @comment sys/stat.h
1989 @comment BSD
1990 @itemx S_IEXEC
1991 @vindex S_IEXEC
1992 Execute (for ordinary files) or search (for directories) permission bit
1993 for the owner of the file.  Usually 0100.  @code{S_IEXEC} is an obsolete
1994 synonym provided for BSD compatibility.
1996 @comment sys/stat.h
1997 @comment POSIX.1
1998 @item S_IRWXU
1999 @vindex S_IRWXU
2000 This is equivalent to @samp{(S_IRUSR | S_IWUSR | S_IXUSR)}.
2002 @comment sys/stat.h
2003 @comment POSIX.1
2004 @item S_IRGRP
2005 @vindex S_IRGRP
2006 Read permission bit for the group owner of the file.  Usually 040.
2008 @comment sys/stat.h
2009 @comment POSIX.1
2010 @item S_IWGRP
2011 @vindex S_IWGRP
2012 Write permission bit for the group owner of the file.  Usually 020.
2014 @comment sys/stat.h
2015 @comment POSIX.1
2016 @item S_IXGRP
2017 @vindex S_IXGRP
2018 Execute or search permission bit for the group owner of the file.
2019 Usually 010.
2021 @comment sys/stat.h
2022 @comment POSIX.1
2023 @item S_IRWXG
2024 @vindex S_IRWXG
2025 This is equivalent to @samp{(S_IRGRP | S_IWGRP | S_IXGRP)}.
2027 @comment sys/stat.h
2028 @comment POSIX.1
2029 @item S_IROTH
2030 @vindex S_IROTH
2031 Read permission bit for other users.  Usually 04.
2033 @comment sys/stat.h
2034 @comment POSIX.1
2035 @item S_IWOTH
2036 @vindex S_IWOTH
2037 Write permission bit for other users.  Usually 02.
2039 @comment sys/stat.h
2040 @comment POSIX.1
2041 @item S_IXOTH
2042 @vindex S_IXOTH
2043 Execute or search permission bit for other users.  Usually 01.
2045 @comment sys/stat.h
2046 @comment POSIX.1
2047 @item S_IRWXO
2048 @vindex S_IRWXO
2049 This is equivalent to @samp{(S_IROTH | S_IWOTH | S_IXOTH)}.
2051 @comment sys/stat.h
2052 @comment POSIX
2053 @item S_ISUID
2054 @vindex S_ISUID
2055 This is the set-user-ID on execute bit, usually 04000.
2056 @xref{How Change Persona}.
2058 @comment sys/stat.h
2059 @comment POSIX
2060 @item S_ISGID
2061 @vindex S_ISGID
2062 This is the set-group-ID on execute bit, usually 02000.
2063 @xref{How Change Persona}.
2065 @cindex sticky bit
2066 @comment sys/stat.h
2067 @comment BSD
2068 @item S_ISVTX
2069 @vindex S_ISVTX
2070 This is the @dfn{sticky} bit, usually 01000.
2072 For a directory it gives permission to delete a file in that directory
2073 only if you own that file.  Ordinarily, a user can either delete all the
2074 files in a directory or cannot delete any of them (based on whether the
2075 user has write permission for the directory).  The same restriction
2076 applies---you must have both write permission for the directory and own
2077 the file you want to delete.  The one exception is that the owner of the
2078 directory can delete any file in the directory, no matter who owns it
2079 (provided the owner has given himself write permission for the
2080 directory).  This is commonly used for the @file{/tmp} directory, where
2081 anyone may create files but not delete files created by other users.
2083 Originally the sticky bit on an executable file modified the swapping
2084 policies of the system.  Normally, when a program terminated, its pages
2085 in core were immediately freed and reused.  If the sticky bit was set on
2086 the executable file, the system kept the pages in core for a while as if
2087 the program were still running.  This was advantageous for a program
2088 likely to be run many times in succession.  This usage is obsolete in
2089 modern systems.  When a program terminates, its pages always remain in
2090 core as long as there is no shortage of memory in the system.  When the
2091 program is next run, its pages will still be in core if no shortage
2092 arose since the last run.
2094 On some modern systems where the sticky bit has no useful meaning for an
2095 executable file, you cannot set the bit at all for a non-directory.
2096 If you try, @code{chmod} fails with @code{EFTYPE};
2097 @pxref{Setting Permissions}.
2099 Some systems (particularly SunOS) have yet another use for the sticky
2100 bit.  If the sticky bit is set on a file that is @emph{not} executable,
2101 it means the opposite: never cache the pages of this file at all.  The
2102 main use of this is for the files on an NFS server machine which are
2103 used as the swap area of diskless client machines.  The idea is that the
2104 pages of the file will be cached in the client's memory, so it is a
2105 waste of the server's memory to cache them a second time.  With this
2106 usage the sticky bit also implies that the filesystem may fail to record
2107 the file's modification time onto disk reliably (the idea being that
2108 no-one cares for a swap file).
2110 This bit is only available on BSD systems (and those derived from
2111 them).  Therefore one has to use the @code{_BSD_SOURCE} feature select
2112 macro to get the definition (@pxref{Feature Test Macros}).
2113 @end table
2115 The actual bit values of the symbols are listed in the table above
2116 so you can decode file mode values when debugging your programs.
2117 These bit values are correct for most systems, but they are not
2118 guaranteed.
2120 @strong{Warning:} Writing explicit numbers for file permissions is bad
2121 practice.  Not only is it not portable, it also requires everyone who
2122 reads your program to remember what the bits mean.  To make your program
2123 clean use the symbolic names.
2125 @node Access Permission
2126 @subsection How Your Access to a File is Decided
2127 @cindex permission to access a file
2128 @cindex access permission for a file
2129 @cindex file access permission
2131 Recall that the operating system normally decides access permission for
2132 a file based on the effective user and group IDs of the process and its
2133 supplementary group IDs, together with the file's owner, group and
2134 permission bits.  These concepts are discussed in detail in @ref{Process
2135 Persona}.
2137 If the effective user ID of the process matches the owner user ID of the
2138 file, then permissions for read, write, and execute/search are
2139 controlled by the corresponding ``user'' (or ``owner'') bits.  Likewise,
2140 if any of the effective group ID or supplementary group IDs of the
2141 process matches the group owner ID of the file, then permissions are
2142 controlled by the ``group'' bits.  Otherwise, permissions are controlled
2143 by the ``other'' bits.
2145 Privileged users, like @samp{root}, can access any file regardless of
2146 its permission bits.  As a special case, for a file to be executable
2147 even by a privileged user, at least one of its execute bits must be set.
2149 @node Setting Permissions
2150 @subsection Assigning File Permissions
2152 @cindex file creation mask
2153 @cindex umask
2154 The primitive functions for creating files (for example, @code{open} or
2155 @code{mkdir}) take a @var{mode} argument, which specifies the file
2156 permissions to give the newly created file.  This mode is modified by
2157 the process's @dfn{file creation mask}, or @dfn{umask}, before it is
2158 used.
2160 The bits that are set in the file creation mask identify permissions
2161 that are always to be disabled for newly created files.  For example, if
2162 you set all the ``other'' access bits in the mask, then newly created
2163 files are not accessible at all to processes in the ``other'' category,
2164 even if the @var{mode} argument passed to the create function would
2165 permit such access.  In other words, the file creation mask is the
2166 complement of the ordinary access permissions you want to grant.
2168 Programs that create files typically specify a @var{mode} argument that
2169 includes all the permissions that make sense for the particular file.
2170 For an ordinary file, this is typically read and write permission for
2171 all classes of users.  These permissions are then restricted as
2172 specified by the individual user's own file creation mask.
2174 @findex chmod
2175 To change the permission of an existing file given its name, call
2176 @code{chmod}.  This function uses the specified permission bits and
2177 ignores the file creation mask.
2179 @pindex umask
2180 In normal use, the file creation mask is initialized by the user's login
2181 shell (using the @code{umask} shell command), and inherited by all
2182 subprocesses.  Application programs normally don't need to worry about
2183 the file creation mask.  It will automatically do what it is supposed to
2186 When your program needs to create a file and bypass the umask for its
2187 access permissions, the easiest way to do this is to use @code{fchmod}
2188 after opening the file, rather than changing the umask.  In fact,
2189 changing the umask is usually done only by shells.  They use the
2190 @code{umask} function.
2192 The functions in this section are declared in @file{sys/stat.h}.
2193 @pindex sys/stat.h
2195 @comment sys/stat.h
2196 @comment POSIX.1
2197 @deftypefun mode_t umask (mode_t @var{mask})
2198 The @code{umask} function sets the file creation mask of the current
2199 process to @var{mask}, and returns the previous value of the file
2200 creation mask.
2202 Here is an example showing how to read the mask with @code{umask}
2203 without changing it permanently:
2205 @smallexample
2206 mode_t
2207 read_umask (void)
2209   mode_t mask = umask (0);
2210   umask (mask);
2211   return mask;
2213 @end smallexample
2215 @noindent
2216 However, it is better to use @code{getumask} if you just want to read
2217 the mask value, because it is reentrant (at least if you use the GNU
2218 operating system).
2219 @end deftypefun
2221 @comment sys/stat.h
2222 @comment GNU
2223 @deftypefun mode_t getumask (void)
2224 Return the current value of the file creation mask for the current
2225 process.  This function is a GNU extension.
2226 @end deftypefun
2228 @comment sys/stat.h
2229 @comment POSIX.1
2230 @deftypefun int chmod (const char *@var{filename}, mode_t @var{mode})
2231 The @code{chmod} function sets the access permission bits for the file
2232 named by @var{filename} to @var{mode}.
2234 If @var{filename} is a symbolic link, @code{chmod} changes the
2235 permissions of the file pointed to by the link, not those of the link
2236 itself.
2238 This function returns @code{0} if successful and @code{-1} if not.  In
2239 addition to the usual file name errors (@pxref{File Name
2240 Errors}), the following @code{errno} error conditions are defined for
2241 this function:
2243 @table @code
2244 @item ENOENT
2245 The named file doesn't exist.
2247 @item EPERM
2248 This process does not have permission to change the access permissions
2249 of this file.  Only the file's owner (as judged by the effective user ID
2250 of the process) or a privileged user can change them.
2252 @item EROFS
2253 The file resides on a read-only file system.
2255 @item EFTYPE
2256 @var{mode} has the @code{S_ISVTX} bit (the ``sticky bit'') set,
2257 and the named file is not a directory.  Some systems do not allow setting the
2258 sticky bit on non-directory files, and some do (and only some of those
2259 assign a useful meaning to the bit for non-directory files).
2261 You only get @code{EFTYPE} on systems where the sticky bit has no useful
2262 meaning for non-directory files, so it is always safe to just clear the
2263 bit in @var{mode} and call @code{chmod} again.  @xref{Permission Bits},
2264 for full details on the sticky bit.
2265 @end table
2266 @end deftypefun
2268 @comment sys/stat.h
2269 @comment BSD
2270 @deftypefun int fchmod (int @var{filedes}, int @var{mode})
2271 This is like @code{chmod}, except that it changes the permissions of the
2272 currently open file given by @var{filedes}.
2274 The return value from @code{fchmod} is @code{0} on success and @code{-1}
2275 on failure.  The following @code{errno} error codes are defined for this
2276 function:
2278 @table @code
2279 @item EBADF
2280 The @var{filedes} argument is not a valid file descriptor.
2282 @item EINVAL
2283 The @var{filedes} argument corresponds to a pipe or socket, or something
2284 else that doesn't really have access permissions.
2286 @item EPERM
2287 This process does not have permission to change the access permissions
2288 of this file.  Only the file's owner (as judged by the effective user ID
2289 of the process) or a privileged user can change them.
2291 @item EROFS
2292 The file resides on a read-only file system.
2293 @end table
2294 @end deftypefun
2296 @node Testing File Access
2297 @subsection Testing Permission to Access a File
2298 @cindex testing access permission
2299 @cindex access, testing for
2300 @cindex setuid programs and file access
2302 In some situations it is desirable to allow programs to access files or
2303 devices even if this is not possible with the permissions granted to the
2304 user.  One possible solution is to set the setuid-bit of the program
2305 file.  If such a program is started the @emph{effective} user ID of the
2306 process is changed to that of the owner of the program file.  So to
2307 allow write access to files like @file{/etc/passwd}, which normally can
2308 be written only by the super-user, the modifying program will have to be
2309 owned by @code{root} and the setuid-bit must be set.
2311 But beside the files the program is intended to change the user should
2312 not be allowed to access any file to which s/he would not have access
2313 anyway.  The program therefore must explicitly check whether @emph{the
2314 user} would have the necessary access to a file, before it reads or
2315 writes the file.
2317 To do this, use the function @code{access}, which checks for access
2318 permission based on the process's @emph{real} user ID rather than the
2319 effective user ID.  (The setuid feature does not alter the real user ID,
2320 so it reflects the user who actually ran the program.)
2322 There is another way you could check this access, which is easy to
2323 describe, but very hard to use.  This is to examine the file mode bits
2324 and mimic the system's own access computation.  This method is
2325 undesirable because many systems have additional access control
2326 features; your program cannot portably mimic them, and you would not
2327 want to try to keep track of the diverse features that different systems
2328 have.  Using @code{access} is simple and automatically does whatever is
2329 appropriate for the system you are using.
2331 @code{access} is @emph{only} only appropriate to use in setuid programs.
2332 A non-setuid program will always use the effective ID rather than the
2333 real ID.
2335 @pindex unistd.h
2336 The symbols in this section are declared in @file{unistd.h}.
2338 @comment unistd.h
2339 @comment POSIX.1
2340 @deftypefun int access (const char *@var{filename}, int @var{how})
2341 The @code{access} function checks to see whether the file named by
2342 @var{filename} can be accessed in the way specified by the @var{how}
2343 argument.  The @var{how} argument either can be the bitwise OR of the
2344 flags @code{R_OK}, @code{W_OK}, @code{X_OK}, or the existence test
2345 @code{F_OK}.
2347 This function uses the @emph{real} user and group IDs of the calling
2348 process, rather than the @emph{effective} IDs, to check for access
2349 permission.  As a result, if you use the function from a @code{setuid}
2350 or @code{setgid} program (@pxref{How Change Persona}), it gives
2351 information relative to the user who actually ran the program.
2353 The return value is @code{0} if the access is permitted, and @code{-1}
2354 otherwise.  (In other words, treated as a predicate function,
2355 @code{access} returns true if the requested access is @emph{denied}.)
2357 In addition to the usual file name errors (@pxref{File Name
2358 Errors}), the following @code{errno} error conditions are defined for
2359 this function:
2361 @table @code
2362 @item EACCES
2363 The access specified by @var{how} is denied.
2365 @item ENOENT
2366 The file doesn't exist.
2368 @item EROFS
2369 Write permission was requested for a file on a read-only file system.
2370 @end table
2371 @end deftypefun
2373 These macros are defined in the header file @file{unistd.h} for use
2374 as the @var{how} argument to the @code{access} function.  The values
2375 are integer constants.
2376 @pindex unistd.h
2378 @comment unistd.h
2379 @comment POSIX.1
2380 @deftypevr Macro int R_OK
2381 Flag meaning test for read permission.
2382 @end deftypevr
2384 @comment unistd.h
2385 @comment POSIX.1
2386 @deftypevr Macro int W_OK
2387 Flag meaning test for write permission.
2388 @end deftypevr
2390 @comment unistd.h
2391 @comment POSIX.1
2392 @deftypevr Macro int X_OK
2393 Flag meaning test for execute/search permission.
2394 @end deftypevr
2396 @comment unistd.h
2397 @comment POSIX.1
2398 @deftypevr Macro int F_OK
2399 Flag meaning test for existence of the file.
2400 @end deftypevr
2402 @node File Times
2403 @subsection File Times
2405 @cindex file access time
2406 @cindex file modification time
2407 @cindex file attribute modification time
2408 Each file has three time stamps associated with it:  its access time,
2409 its modification time, and its attribute modification time.  These
2410 correspond to the @code{st_atime}, @code{st_mtime}, and @code{st_ctime}
2411 members of the @code{stat} structure; see @ref{File Attributes}.
2413 All of these times are represented in calendar time format, as
2414 @code{time_t} objects.  This data type is defined in @file{time.h}.
2415 For more information about representation and manipulation of time
2416 values, see @ref{Calendar Time}.
2417 @pindex time.h
2419 Reading from a file updates its access time attribute, and writing
2420 updates its modification time.  When a file is created, all three
2421 time stamps for that file are set to the current time.  In addition, the
2422 attribute change time and modification time fields of the directory that
2423 contains the new entry are updated.
2425 Adding a new name for a file with the @code{link} function updates the
2426 attribute change time field of the file being linked, and both the
2427 attribute change time and modification time fields of the directory
2428 containing the new name.  These same fields are affected if a file name
2429 is deleted with @code{unlink}, @code{remove} or @code{rmdir}.  Renaming
2430 a file with @code{rename} affects only the attribute change time and
2431 modification time fields of the two parent directories involved, and not
2432 the times for the file being renamed.
2434 Changing the attributes of a file (for example, with @code{chmod})
2435 updates its attribute change time field.
2437 You can also change some of the time stamps of a file explicitly using
2438 the @code{utime} function---all except the attribute change time.  You
2439 need to include the header file @file{utime.h} to use this facility.
2440 @pindex utime.h
2442 @comment time.h
2443 @comment POSIX.1
2444 @deftp {Data Type} {struct utimbuf}
2445 The @code{utimbuf} structure is used with the @code{utime} function to
2446 specify new access and modification times for a file.  It contains the
2447 following members:
2449 @table @code
2450 @item time_t actime
2451 This is the access time for the file.
2453 @item time_t modtime
2454 This is the modification time for the file.
2455 @end table
2456 @end deftp
2458 @comment time.h
2459 @comment POSIX.1
2460 @deftypefun int utime (const char *@var{filename}, const struct utimbuf *@var{times})
2461 This function is used to modify the file times associated with the file
2462 named @var{filename}.
2464 If @var{times} is a null pointer, then the access and modification times
2465 of the file are set to the current time.  Otherwise, they are set to the
2466 values from the @code{actime} and @code{modtime} members (respectively)
2467 of the @code{utimbuf} structure pointed to by @var{times}.
2469 The attribute modification time for the file is set to the current time
2470 in either case (since changing the time stamps is itself a modification
2471 of the file attributes).
2473 The @code{utime} function returns @code{0} if successful and @code{-1}
2474 on failure.  In addition to the usual file name errors
2475 (@pxref{File Name Errors}), the following @code{errno} error conditions
2476 are defined for this function:
2478 @table @code
2479 @item EACCES
2480 There is a permission problem in the case where a null pointer was
2481 passed as the @var{times} argument.  In order to update the time stamp on
2482 the file, you must either be the owner of the file, have write
2483 permission for the file, or be a privileged user.
2485 @item ENOENT
2486 The file doesn't exist.
2488 @item EPERM
2489 If the @var{times} argument is not a null pointer, you must either be
2490 the owner of the file or be a privileged user.
2492 @item EROFS
2493 The file lives on a read-only file system.
2494 @end table
2495 @end deftypefun
2497 Each of the three time stamps has a corresponding microsecond part,
2498 which extends its resolution.  These fields are called
2499 @code{st_atime_usec}, @code{st_mtime_usec}, and @code{st_ctime_usec};
2500 each has a value between 0 and 999,999, which indicates the time in
2501 microseconds.  They correspond to the @code{tv_usec} field of a
2502 @code{timeval} structure; see @ref{High-Resolution Calendar}.
2504 The @code{utimes} function is like @code{utime}, but also lets you specify
2505 the fractional part of the file times.  The prototype for this function is
2506 in the header file @file{sys/time.h}.
2507 @pindex sys/time.h
2509 @comment sys/time.h
2510 @comment BSD
2511 @deftypefun int utimes (const char *@var{filename}, struct timeval @var{tvp}@t{[2]})
2512 This function sets the file access and modification times of the file
2513 @var{filename}.  The new file access time is specified by
2514 @code{@var{tvp}[0]}, and the new modification time by
2515 @code{@var{tvp}[1]}.  This function comes from BSD.
2517 The return values and error conditions are the same as for the @code{utime}
2518 function.
2519 @end deftypefun
2521 @node File Size
2522 @subsection File Size
2524 Normally file sizes are maintained automatically.  A file begins with a
2525 size of @math{0} and is automatically extended when data is written past
2526 its end.  It is also possible to empty a file completely by an
2527 @code{open} or @code{fopen} call.
2529 However, sometimes it is necessary to @emph{reduce} the size of a file.
2530 This can be done with the @code{truncate} and @code{ftruncate} functions.
2531 They were introduced in BSD Unix.  @code{ftruncate} was later added to
2532 POSIX.1.
2534 Some systems allow you to extend a file (creating holes) with these
2535 functions.  This is useful when using memory-mapped I/O
2536 (@pxref{Memory-mapped I/O}), where files are not automatically extended.
2537 However, it is not portable but must be implemented if @code{mmap}
2538 allows mapping of files (i.e., @code{_POSIX_MAPPED_FILES} is defined).
2540 Using these functions on anything other than a regular file gives
2541 @emph{undefined} results.  On many systems, such a call will appear to
2542 succeed, without actually accomplishing anything.
2544 @comment unistd.h
2545 @comment X/Open
2546 @deftypefun int truncate (const char *@var{filename}, off_t @var{length})
2548 The @code{truncate} function changes the size of @var{filename} to
2549 @var{length}.  If @var{length} is shorter than the previous length, data
2550 at the end will be lost.  The file must be writable by the user to
2551 perform this operation.
2553 If @var{length} is longer, holes will be added to the end.  However, some
2554 systems do not support this feature and will leave the file unchanged.
2556 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
2557 @code{truncate} function is in fact @code{truncate64} and the type
2558 @code{off_t} has 64 bits which makes it possible to handle files up to
2559 @math{2^63} bytes in length.
2561 The return value is @math{0} for success, or @math{-1} for an error.  In
2562 addition to the usual file name errors, the following errors may occur:
2564 @table @code
2566 @item EACCES
2567 The file is a directory or not writable.
2569 @item EINVAL
2570 @var{length} is negative.
2572 @item EFBIG
2573 The operation would extend the file beyond the limits of the operating system.
2575 @item EIO
2576 A hardware I/O error occurred.
2578 @item EPERM
2579 The file is "append-only" or "immutable".
2581 @item EINTR
2582 The operation was interrupted by a signal.
2584 @end table
2586 @end deftypefun
2588 @comment unistd.h
2589 @comment Unix98
2590 @deftypefun int truncate64 (const char *@var{name}, off64_t @var{length})
2591 This function is similar to the @code{truncate} function.  The
2592 difference is that the @var{length} argument is 64 bits wide even on 32
2593 bits machines, which allows the handling of files with sizes up to
2594 @math{2^63} bytes.
2596 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
2597 32 bits machine this function is actually available under the name
2598 @code{truncate} and so transparently replaces the 32 bits interface.
2599 @end deftypefun
2601 @comment unistd.h
2602 @comment POSIX
2603 @deftypefun int ftruncate (int @var{fd}, off_t @var{length})
2605 This is like @code{truncate}, but it works on a file descriptor @var{fd}
2606 for an opened file instead of a file name to identify the object.  The
2607 file must be opened for writing to successfully carry out the operation.
2609 The POSIX standard leaves it implementation defined what happens if the
2610 specified new @var{length} of the file is bigger than the original size.
2611 The @code{ftruncate} function might simply leave the file alone and do
2612 nothing or it can increase the size to the desired size.  In this later
2613 case the extended area should be zero-filled.  So using @code{ftruncate}
2614 is no reliable way to increase the file size but if it is possible it is
2615 probably the fastest way.  The function also operates on POSIX shared
2616 memory segments if these are implemented by the system.
2618 @code{ftruncate} is especially useful in combination with @code{mmap}.
2619 Since the mapped region must have a fixed size one cannot enlarge the
2620 file by writing something beyond the last mapped page.  Instead one has
2621 to enlarge the file itself and then remap the file with the new size.
2622 The example below shows how this works.
2624 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
2625 @code{ftruncate} function is in fact @code{ftruncate64} and the type
2626 @code{off_t} has 64 bits which makes it possible to handle files up to
2627 @math{2^63} bytes in length.
2629 The return value is @math{0} for success, or @math{-1} for an error.  The
2630 following errors may occur:
2632 @table @code
2634 @item EBADF
2635 @var{fd} does not correspond to an open file.
2637 @item EACCES
2638 @var{fd} is a directory or not open for writing.
2640 @item EINVAL
2641 @var{length} is negative.
2643 @item EFBIG
2644 The operation would extend the file beyond the limits of the operating system.
2645 @c or the open() call -- with the not-yet-discussed feature of opening
2646 @c files with extra-large offsets.
2648 @item EIO
2649 A hardware I/O error occurred.
2651 @item EPERM
2652 The file is "append-only" or "immutable".
2654 @item EINTR
2655 The operation was interrupted by a signal.
2657 @c ENOENT is also possible on Linux --- however it only occurs if the file
2658 @c descriptor has a `file' structure but no `inode' structure.  I'm not
2659 @c sure how such an fd could be created.  Perhaps it's a bug.
2661 @end table
2663 @end deftypefun
2665 @comment unistd.h
2666 @comment Unix98
2667 @deftypefun int ftruncate64 (int @var{id}, off64_t @var{length})
2668 This function is similar to the @code{ftruncate} function.  The
2669 difference is that the @var{length} argument is 64 bits wide even on 32
2670 bits machines which allows the handling of files with sizes up to
2671 @math{2^63} bytes.
2673 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
2674 32 bits machine this function is actually available under the name
2675 @code{ftruncate} and so transparently replaces the 32 bits interface.
2676 @end deftypefun
2678 As announced here is a little example of how to use @code{ftruncate} in
2679 combination with @code{mmap}:
2681 @smallexample
2682 int fd;
2683 void *start;
2684 size_t len;
2687 add (off_t at, void *block, size_t size)
2689   if (at + size > len)
2690     @{
2691       /* Resize the file and remap.  */
2692       size_t ps = sysconf (_SC_PAGESIZE);
2693       size_t ns = (at + size + ps - 1) & ~(ps - 1);
2694       void *np;
2695       if (ftruncate (fd, ns) < 0)
2696         return -1;
2697       np = mmap (NULL, ns, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
2698       if (np == MAP_FAILED)
2699         return -1;
2700       start = np;
2701       len = ns;
2702     @}
2703   memcpy ((char *) start + at, block, size);
2704   return 0;
2706 @end smallexample
2708 The function @code{add} writes a block of memory at an arbitrary
2709 position in the file.  If the current size of the file is too small it
2710 is extended.  Note the it is extended by a round number of pages.  This
2711 is a requirement of @code{mmap}.  The program has to keep track of the
2712 real size, and when it has finished a final @code{ftruncate} call should
2713 set the real size of the file.
2715 @node Making Special Files
2716 @section Making Special Files
2717 @cindex creating special files
2718 @cindex special files
2720 The @code{mknod} function is the primitive for making special files,
2721 such as files that correspond to devices.  The GNU library includes
2722 this function for compatibility with BSD.
2724 The prototype for @code{mknod} is declared in @file{sys/stat.h}.
2725 @pindex sys/stat.h
2727 @comment sys/stat.h
2728 @comment BSD
2729 @deftypefun int mknod (const char *@var{filename}, int @var{mode}, int @var{dev})
2730 The @code{mknod} function makes a special file with name @var{filename}.
2731 The @var{mode} specifies the mode of the file, and may include the various
2732 special file bits, such as @code{S_IFCHR} (for a character special file)
2733 or @code{S_IFBLK} (for a block special file).  @xref{Testing File Type}.
2735 The @var{dev} argument specifies which device the special file refers to.
2736 Its exact interpretation depends on the kind of special file being created.
2738 The return value is @code{0} on success and @code{-1} on error.  In addition
2739 to the usual file name errors (@pxref{File Name Errors}), the
2740 following @code{errno} error conditions are defined for this function:
2742 @table @code
2743 @item EPERM
2744 The calling process is not privileged.  Only the superuser can create
2745 special files.
2747 @item ENOSPC
2748 The directory or file system that would contain the new file is full
2749 and cannot be extended.
2751 @item EROFS
2752 The directory containing the new file can't be modified because it's on
2753 a read-only file system.
2755 @item EEXIST
2756 There is already a file named @var{filename}.  If you want to replace
2757 this file, you must remove the old file explicitly first.
2758 @end table
2759 @end deftypefun
2761 @node Temporary Files
2762 @section Temporary Files
2764 If you need to use a temporary file in your program, you can use the
2765 @code{tmpfile} function to open it.  Or you can use the @code{tmpnam}
2766 (better: @code{tmpnam_r}) function to provide a name for a temporary
2767 file and then you can open it in the usual way with @code{fopen}.
2769 The @code{tempnam} function is like @code{tmpnam} but lets you choose
2770 what directory temporary files will go in, and something about what
2771 their file names will look like.  Important for multi-threaded programs
2772 is that @code{tempnam} is reentrant, while @code{tmpnam} is not since it
2773 returns a pointer to a static buffer.
2775 These facilities are declared in the header file @file{stdio.h}.
2776 @pindex stdio.h
2778 @comment stdio.h
2779 @comment ISO
2780 @deftypefun {FILE *} tmpfile (void)
2781 This function creates a temporary binary file for update mode, as if by
2782 calling @code{fopen} with mode @code{"wb+"}.  The file is deleted
2783 automatically when it is closed or when the program terminates.  (On
2784 some other @w{ISO C} systems the file may fail to be deleted if the program
2785 terminates abnormally).
2787 This function is reentrant.
2789 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
2790 32-bit system this function is in fact @code{tmpfile64}, i.e. the LFS
2791 interface transparently replaces the old interface.
2792 @end deftypefun
2794 @comment stdio.h
2795 @comment Unix98
2796 @deftypefun {FILE *} tmpfile64 (void)
2797 This function is similar to @code{tmpfile}, but the stream it returns a
2798 pointer to was opened using @code{tmpfile64}.  Therefore this stream can
2799 be used for files larger then @math{2^31} bytes on 32-bit machines.
2801 Please note that the return type is still @code{FILE *}.  There is no
2802 special @code{FILE} type for the LFS interface.
2804 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
2805 bits machine this function is available under the name @code{tmpfile}
2806 and so transparently replaces the old interface.
2807 @end deftypefun
2809 @comment stdio.h
2810 @comment ISO
2811 @deftypefun {char *} tmpnam (char *@var{result})
2812 This function constructs and returns a valid file name that does not
2813 refer to any existing file.  If the @var{result} argument is a null
2814 pointer, the return value is a pointer to an internal static string,
2815 which might be modified by subsequent calls and therefore makes this
2816 function non-reentrant.  Otherwise, the @var{result} argument should be
2817 a pointer to an array of at least @code{L_tmpnam} characters, and the
2818 result is written into that array.
2820 It is possible for @code{tmpnam} to fail if you call it too many times
2821 without removing previously-created files.  This is because the limited
2822 length of the temporary file names gives room for only a finite number
2823 of different names.  If @code{tmpnam} fails it returns a null pointer.
2825 @strong{Warning:} Between the time the pathname is constructed and the
2826 file is created another process might have created a file with the same
2827 name using @code{tmpnam}, leading to a possible security hole.  The
2828 implementation generates names which can hardly be predicted, but when
2829 opening the file you should use the @code{O_EXCL} flag.  Using
2830 @code{tmpfile} is a safe way to avoid this problem.
2831 @end deftypefun
2833 @comment stdio.h
2834 @comment GNU
2835 @deftypefun {char *} tmpnam_r (char *@var{result})
2836 This function is nearly identical to the @code{tmpnam} function, except
2837 that if @var{result} is a null pointer it returns a null pointer.
2839 This guarantees reentrancy because the non-reentrant situation of
2840 @code{tmpnam} cannot happen here.
2841 @end deftypefun
2843 @comment stdio.h
2844 @comment ISO
2845 @deftypevr Macro int L_tmpnam
2846 The value of this macro is an integer constant expression that
2847 represents the minimum size of a string large enough to hold a file name
2848 generated by the @code{tmpnam} function.
2849 @end deftypevr
2851 @comment stdio.h
2852 @comment ISO
2853 @deftypevr Macro int TMP_MAX
2854 The macro @code{TMP_MAX} is a lower bound for how many temporary names
2855 you can create with @code{tmpnam}.  You can rely on being able to call
2856 @code{tmpnam} at least this many times before it might fail saying you
2857 have made too many temporary file names.
2859 With the GNU library, you can create a very large number of temporary
2860 file names.  If you actually created the files, you would probably run
2861 out of disk space before you ran out of names.  Some other systems have
2862 a fixed, small limit on the number of temporary files.  The limit is
2863 never less than @code{25}.
2864 @end deftypevr
2866 @comment stdio.h
2867 @comment SVID
2868 @deftypefun {char *} tempnam (const char *@var{dir}, const char *@var{prefix})
2869 This function generates a unique temporary file name.  If @var{prefix}
2870 is not a null pointer, up to five characters of this string are used as
2871 a prefix for the file name.  The return value is a string newly
2872 allocated with @code{malloc}, so you should release its storage with
2873 @code{free} when it is no longer needed.
2875 Because the string is dynamically allocated this function is reentrant.
2877 The directory prefix for the temporary file name is determined by
2878 testing each of the following in sequence.  The directory must exist and
2879 be writable.
2881 @itemize @bullet
2882 @item
2883 The environment variable @code{TMPDIR}, if it is defined.  For security
2884 reasons this only happens if the program is not SUID or SGID enabled.
2886 @item
2887 The @var{dir} argument, if it is not a null pointer.
2889 @item
2890 The value of the @code{P_tmpdir} macro.
2892 @item
2893 The directory @file{/tmp}.
2894 @end itemize
2896 This function is defined for SVID compatibility.
2897 @end deftypefun
2898 @cindex TMPDIR environment variable
2900 @comment stdio.h
2901 @comment SVID
2902 @c !!! are we putting SVID/GNU/POSIX.1/BSD in here or not??
2903 @deftypevr {SVID Macro} {char *} P_tmpdir
2904 This macro is the name of the default directory for temporary files.
2905 @end deftypevr
2907 Older Unix systems did not have the functions just described.  Instead
2908 they used @code{mktemp} and @code{mkstemp}.  Both of these functions
2909 work by modifying a file name template string you pass.  The last six
2910 characters of this string must be @samp{XXXXXX}.  These six @samp{X}s
2911 are replaced with six characters which make the whole string a unique
2912 file name.  Usually the template string is something like
2913 @samp{/tmp/@var{prefix}XXXXXX}, and each program uses a unique @var{prefix}.
2915 @strong{Note:} Because @code{mktemp} and @code{mkstemp} modify the
2916 template string, you @emph{must not} pass string constants to them.
2917 String constants are normally in read-only storage, so your program
2918 would crash when @code{mktemp} or @code{mkstemp} tried to modify the
2919 string.
2921 @comment stdlib.h
2922 @comment Unix
2923 @deftypefun {char *} mktemp (char *@var{template})
2924 The @code{mktemp} function generates a unique file name by modifying
2925 @var{template} as described above.  If successful, it returns
2926 @var{template} as modified.  If @code{mktemp} cannot find a unique file
2927 name, it makes @var{template} an empty string and returns that.  If
2928 @var{template} does not end with @samp{XXXXXX}, @code{mktemp} returns a
2929 null pointer.
2931 @strong{Warning:} Between the time the pathname is constructed and the
2932 file is created another process might have created a file with the same
2933 name using @code{mktemp}, leading to a possible security hole.  The
2934 implementation generates names which can hardly be predicted, but when
2935 opening the file you should use the @code{O_EXCL} flag.  Using
2936 @code{mkstemp} is a safe way to avoid this problem.
2937 @end deftypefun
2939 @comment stdlib.h
2940 @comment BSD
2941 @deftypefun int mkstemp (char *@var{template})
2942 The @code{mkstemp} function generates a unique file name just as
2943 @code{mktemp} does, but it also opens the file for you with @code{open}
2944 (@pxref{Opening and Closing Files}).  If successful, it modifies
2945 @var{template} in place and returns a file descriptor for that file open
2946 for reading and writing.  If @code{mkstemp} cannot create a
2947 uniquely-named file, it returns @code{-1}.  If @var{template} does not
2948 end with @samp{XXXXXX}, @code{mkstemp} returns @code{-1} and does not
2949 modify @var{template}.
2951 The file is opened using mode @code{0600}.  If the file is meant to be
2952 used by other users this mode must be changed explicitly.
2953 @end deftypefun
2955 Unlike @code{mktemp}, @code{mkstemp} is actually guaranteed to create a
2956 unique file that cannot possibly clash with any other program trying to
2957 create a temporary file.  This is because it works by calling
2958 @code{open} with the @code{O_EXCL} flag, which says you want to create a
2959 new file and get an error if the file already exists.
2961 @comment stdlib.h
2962 @comment BSD
2963 @deftypefun {char *} mkdtemp (char *@var{template})
2964 The @code{mkdtemp} function creates a directory with a unique name.  If
2965 it succeeds, it overwrites @var{template} with the name of the
2966 directory, and returns @var{template}.  As with @code{mktemp} and
2967 @code{mkstemp}, @var{template} should be a string ending with
2968 @samp{XXXXXX}.
2970 If @code{mkdtemp} cannot create an uniquely named directory, it returns
2971 @code{NULL} and sets @var{errno} appropriately.  If @var{template} does
2972 not end with @samp{XXXXXX}, @code{mkdtemp} returns @code{NULL} and does
2973 not modify @var{template}.  @var{errno} will be set to @code{EINVAL} in
2974 this case.
2976 The directory is created using mode @code{0700}.
2977 @end deftypefun
2979 The directory created by @code{mkdtemp} cannot clash with temporary
2980 files or directories created by other users.  This is because directory
2981 creation always works like @code{open} with @code{O_EXCL}.
2982 @xref{Creating Directories}.
2984 The @code{mkdtemp} function comes from OpenBSD.