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