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