@Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.
Œ

ˆ‰SEC148Št�”›File System Interface

@�”˜This chapter describes the GNU C library's functions for manipulating files. Unlike the input and output functions described in section ‰ŠP�”›Input/Output on Streams@�”˜ and section ‰ŠP�”›Low-Level Input/Output@�”˜, these functions are concerned with operating on the files themselves, rather than on their contents.
Among the facilities described in this chapter are functions for examining or modifying directories, functions for renaming and deleting files, and functions for examining and setting file attributes such as access permissions and modification times.
ˆ‰SEC149Št�”›Working Directory

‰IDX732Š‰IDX733Š‰IDX734Š@�”˜Each process has associated with it a directory, called its Bcurrent working directory@ or simply Bworking directory@, that is used in the resolution of relative file names (see section ‰ŠP�”›File Name Resolution@�”˜).
When you log in and begin a new session, your working directory is initially set to the home directory associated with your login account in the system user database. You can find any user's home directory using the Hgetpwuid@ or Hgetpwnam@ functions; see section ‰ŠP�”›User Database@�”˜.
Users can change the working directory using shell commands like Hcd@. The functions described in this section are the primitives used by those commands and by other programs for examining and changing the working directory. ‰IDX735Š
@�”˜Prototypes for these functions are declared in the header file H`unistd.h'@. ‰IDX736Š

A�”˜Function:@ char * Dgetcwd@ B(char *Bbuffer@, size_t Bsize@)
Â‰IDX737Š@�”˜The Hgetcwd@ function returns an absolute file name representing the current working directory, storing it in the character array Bbuffer@ that you provide. The Bsize@ argument is how you tell the system the allocation size of Bbuffer@.
The GNU library version of this function also permits you to specify a null pointer for the Bbuffer@ argument. Then Hgetcwd@ allocates a buffer automatically, as with Hmalloc@ (see section ‰ŠP�”›Unconstrained Allocation@�”˜). If the Bsize@ is greater than zero, then the buffer is that large; otherwise, the buffer is as large as necessary to hold the result.
The return value is Bbuffer@ on success and a null pointer on failure. The following Herrno@ error conditions are defined for this function:
HEINVAL
Ä@The Bsize@ argument is zero and Bbuffer@ is not a null pointer.
ÂHERANGE
Ä@The Bsize@ argument is less than the length of the working directory name. You need to allocate a bigger array and try again.
ÂHEACCES
Ä@Permission to read or search a component of the file name was denied.Â
À

Here is an example showing how you could implement the behavior of GNU's Hgetcwd (NULL, 0)@ using only the standard behavior of Hgetcwd@: char *
gnu_getcwd ()
{
int size = 100;
char *buffer = (char *) xmalloc (size);

while (1)
{
char *value = getcwd (buffer, size);
if (value != 0)
return buffer;
size *= 2;
free (buffer);
buffer = (char *) xmalloc (size);
}
}
See section ‰ŠP�”›Examples of Xmalloc@�”˜, for information about Hxmalloc@, which is not a library function but is a customary name used in most GNU software.

AFunction:@ char * Dgetwd@ B(char *Bbuffer@)
Â‰IDX738Š@�”˜This is similar to Hgetcwd@, but has no way to specify the size of the buffer. The GNU library provides Hgetwd@ only for backwards compatibility with BSD.
The Bbuffer@ argument should be a pointer to an array at least HPATH_MAX@ bytes long (see section ‰ŠP�”›Limits on File System Capacity@�”˜). In the GNU system there is no limit to the size of a file name, so this is not necessarily enough space to contain the directory name. That is why this function is deprecated.À

AFunction:@ int Dchdir@ B(const char *Bfilename@)
Â‰IDX739Š@�”˜This function is used to set the process's working directory to Bfilename@.
The normal, successful return value from Hchdir@ is H0@. A value of H-1@ is returned to indicate an error. The Herrno@ error conditions defined for this function are the usual file name syntax errors (see section ‰ŠP�”›File Name Errors@�”˜), plus HENOTDIR@ if the file Bfilename@ is not a directory.À

ˆ‰SEC150Št�”›Accessing Directories

‰IDX740Š‰IDX741Š‰IDX742Š
@�”˜The facilities described in this section let you read the contents of a directory file. This is useful if you want your program to list all the files in a directory, perhaps as part of a menu.
‰IDX743Š@�”˜The Hopendir@ function opens a Bdirectory stream@ whose elements are directory entries. You use the Hreaddir@ function on the directory stream to retrieve these entries, represented as Hstruct dirent@ objects. The name of the file for each entry is stored in the Hd_name@ member of this structure. There are obvious parallels here to the stream facilities for ordinary files, described in section ‰ŠP�”›Input/Output on Streams@�”˜.
ˆ‰SEC151ŠT�”›Format of a Directory Entry

‰IDX744Š@�”˜This section describes what you find in a single directory entry, as you might obtain it from a directory stream. All the symbols are declared in the header file H`dirent.h'@.

AData Type:@ Dstruct dirent
Â‰IDX745Š@�”˜This is a structure type used to return information about directory entries. It contains the following fields:
Hchar d_name[]
Ä@This is the null-terminated file name component. This is the only field you can count on in all POSIX systems.
ÂHino_t d_fileno
Ä@This is the file serial number. For BSD compatibility, you can also refer to this member as Hd_ino@. In the GNU system and most POSIX systems, for most files this the same as the Hst_ino@ member that Hstat@ will return for the file. See section ‰ŠP�”›File Attributes@�”˜.
ÂHunsigned char d_namlen
Ä@This is the length of the file name, not including the terminating null character. Its type is Hunsigned char@ because that is the integer type of the appropriate size
ÂHunsigned char d_type
Ä@This is the type of the file, possibly unknown. The following constants are defined for its value:
HDT_UNKNOWN
Æ@The type is unknown. On some systems this is the only value returned.
ÄHDT_REG
Æ@A regular file.
ÄHDT_DIR
Æ@A directory.
ÄHDT_FIFO
Æ@A named pipe, or FIFO. See section ‰ŠP�”›FIFO Special Files@�”˜.
ÄHDT_SOCK
Æ@A local-domain socket.
ÄHDT_CHR
Æ@A character device.
ÄHDT_BLK
Æ@A block device.Ä
This member is a BSD extension. Each value except DT_UNKNOWN corresponds to the file type bits in the Hst_mode@ member of Hstruct statbuf@. These two macros convert between Hd_type@ values and Hst_mode@ values:
AFunction:@ int DIFTODT@ B(mode_t Bmode@)
Æ‰IDX746Š@�”˜This returns the Hd_type@ value corresponding to Bmode@.Ä

AFunction:@ mode_t DDTTOIF@ B(int Bdirtype@)
Æ‰IDX747Š@�”˜This returns the Hst_mode@ value corresponding to Bdirtype@.Ä
Â

This structure may contain additional members in the future.
When a file has multiple names, each name has its own directory entry. The only way you can tell that the directory entries belong to a single file is that they have the same value for the Hd_fileno@ field.
File attributes such as size, modification times, and the like are part of the file itself, not any particular directory entry. See section ‰ŠP�”›File Attributes@�”˜.À

ˆ‰SEC152ŠT�”›Opening a Directory Stream

‰IDX748Š@�”˜This section describes how to open a directory stream. All the symbols are declared in the header file H`dirent.h'@.

AData Type:@ DDIR
Â‰IDX749Š@�”˜The HDIR@ data type represents a directory stream.À

You shouldn't ever allocate objects of the Hstruct dirent@ or HDIR@ data types, since the directory access functions do that for you. Instead, you refer to these objects using the pointers returned by the following functions.

AFunction:@ DIR * Dopendir@ B(const char *Bdirname@)
Â‰IDX750Š@�”˜The Hopendir@ function opens and returns a directory stream for reading the directory whose file name is Bdirname@. The stream has type HDIR *@.
If unsuccessful, Hopendir@ returns a null pointer. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEACCES
Ä@Read permission is denied for the directory named by Hdirname@.
ÂHEMFILE
Ä@The process has too many files open.
ÂHENFILE
Ä@The entire system, or perhaps the file system which contains the directory, cannot support any additional open files at the moment. (This problem cannot happen on the GNU system.)Â

The HDIR@ type is typically implemented using a file descriptor, and the Hopendir@ function in terms of the Hopen@ function. See section ‰ŠP�”›Low-Level Input/Output@�”˜. Directory streams and the underlying file descriptors are closed on Hexec@ (see section ‰ŠP�”›Executing a File@�”˜).À

ˆ‰SEC153ŠT�”›Reading and Closing a Directory Stream

‰IDX751Š@�”˜This section describes how to read directory entries from a directory stream, and how to close the stream when you are done with it. All the symbols are declared in the header file H`dirent.h'@.

AFunction:@ struct dirent * Dreaddir@ B(DIR *Bdirstream@)
Â‰IDX752Š@�”˜This function reads the next entry from the directory. It normally returns a pointer to a structure containing information about the file. This structure is statically allocated and can be rewritten by a subsequent call.
DPortability Note:@ On some systems, Hreaddir@ may not return entries for H`.'@ and H`..'@, even though these are always valid file names in any directory. See section ‰ŠP�”›File Name Resolution@�”˜.
If there are no more entries in the directory or an error is detected, Hreaddir@ returns a null pointer. The following Herrno@ error conditions are defined for this function:
HEBADF
Ä@The Bdirstream@ argument is not valid.Â

Hreaddir@ is not thread safe. Multiple threads using Hreaddir@ on the same Bdirstream@ may overwrite the return value. Use Hreaddir_r@ when this is critical.À

AFunction:@ int Dreaddir_r@ B(DIR *Bdirstream@, struct dirent *Bentry@, struct dirent **Bresult@)
Â‰IDX753Š@�”˜This function is the reentrant version of Hreaddir@. Like Hreaddir@ it returns the next entry from the directory. But to prevent conflicts for simultaneously running threads the result is not stored in some internal memory. Instead the argument Bentry@ has to point to a place where the result is stored.
The return value is H0@ in case the next entry was read successfully. In this case a pointer to the result is returned in *Bresult@. It is not required that *Bresult@ is the same as Bentry@. If something goes wrong while executing Hreaddir_r@ the function returns H-1@. The Herrno@ variable is set like described for Hreaddir@.
DPortability Note:@ On some systems, Hreaddir_r@ may not return a terminated string as the file name even if no Hd_reclen@ element is available in Hstruct dirent@ and the file name as the maximal allowed size. Modern systems all have the Hd_reclen@ field and on old systems multi threading is not critical. In any case, there is no such problem with the Hreaddir@ function so that even on systems without Hd_reclen@ field one could use multiple threads by using external locking.À

AFunction:@ int Dclosedir@ B(DIR *Bdirstream@)
Â‰IDX754Š@�”˜This function closes the directory stream Bdirstream@. It returns H0@ on success and H-1@ on failure.
The following Herrno@ error conditions are defined for this function:
HEBADF
Ä@The Bdirstream@ argument is not valid.Â
À

ˆ‰SEC154ŠT�”›Simple Program to List a Directory

@�”˜Here's a simple program that prints the names of the files in the current working directory: #include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int
main (void)
{
DIR *dp;
struct dirent *ep;

dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
puts ("Couldn't open the directory.");

return 0;
}
The order in which files appear in a directory tends to be fairly random. A more useful program would sort the entries (perhaps by alphabetizing them) before printing them; see section ‰ŠP�”›Scanning the Content of a Directory@�”˜ and section ‰ŠP�”›Array Sort Function@�”˜.
ˆ‰SEC155ŠT�”›Random Access in a Directory Stream

‰IDX755Š@�”˜This section describes how to reread parts of a directory that you have already read from an open directory stream. All the symbols are declared in the header file H`dirent.h'@.

AFunction:@ void Drewinddir@ B(DIR *Bdirstream@)
Â‰IDX756Š@�”˜The Hrewinddir@ function is used to reinitialize the directory stream Bdirstream@, so that if you call Hreaddir@ it returns information about the first entry in the directory again. This function also notices if files have been added or removed to the directory since it was opened with Hopendir@. (Entries for these files might or might not be returned by Hreaddir@ if they were added or removed since you last called Hopendir@ or Hrewinddir@.)À

AFunction:@ off_t Dtelldir@ B(DIR *Bdirstream@)
Â‰IDX757Š@�”˜The Htelldir@ function returns the file position of the directory stream Bdirstream@. You can use this value with Hseekdir@ to restore the directory stream to that position.À

AFunction:@ void Dseekdir@ B(DIR *Bdirstream@, off_t Bpos@)
Â‰IDX758Š@�”˜The Hseekdir@ function sets the file position of the directory stream Bdirstream@ to Bpos@. The value Bpos@ must be the result of a previous call to Htelldir@ on this particular stream; closing and reopening the directory can invalidate values returned by Htelldir@.À

ˆ‰SEC156ŠT�”›Scanning the Content of a Directory

@�”˜A higher-level interface to the directory handling functions is the Hscandir@ function. With its help one can select a subset of the entries in a directory, possibly sort them and get as the result a list of names.

AFunction:@ int Dscandir@ B(const char *Bdir@, struct dirent ***Bnamelist@, int (*Bselector@) (struct dirent *), int (*Bcmp@) (const void *, const void *))
Â‰IDX759Š
@�”˜The Hscandir@ function scans the contents of the directory selected by Bdir@. The result in Bnamelist@ is an array of pointers to structure of type Hstruct dirent@ which describe all selected directory entries and which is allocated using Hmalloc@. Instead of always getting all directory entries returned, the user supplied function Bselector@ can be used to decide which entries are in the result. Only the entries for which Bselector@ returns a nonzero value are selected.
Finally the entries in the Bnamelist@ are sorted using the user supplied function Bcmp@. The arguments of the Bcmp@ function are of type Hstruct dirent **@. I.e., one cannot directly use the Hstrcmp@ or Hstrcoll@ function; see the function Halphasort@ below.
The return value of the function gives the number of entries placed in Bnamelist@. If it is H-1@ an error occurred and the global variable Herrno@ contains more information on the error.À

As said above the fourth argument to the Hscandir@ function must be a pointer to a sorting function. For the convenience of the programmer the GNU C library contains an implementation of a function which is very helpful for this purpose.

AFunction:@ int Dalphasort@ B(const void *Ba@, const void *Bb@)
Â‰IDX760Š@�”˜The Halphasort@ function behaves like the Hstrcmp@ function (see section ‰ŠP�”›String/Array Comparison@�”˜). The difference is that the arguments are not string pointers but instead they are of type Hstruct dirent **@.
Return value of is less than, equal to, or greater than zero depending on the order of the two entries Ba@ and Bb@.À

ˆ‰SEC157ŠT�”›Simple Program to List a Directory, Mark II

@�”˜Here is a revised version of the directory lister found above (see section ‰ŠP�”›Simple Program to List a Directory@�”˜). Using the Hscandir@ function we can avoid using the functions which directly work with the directory contents. After the call the found entries are available for direct used. #include <stdio.h>
#include <dirent.h>

static int
one (struct dirent *unused)
{
return 1;
}

int
main (void)
{
struct dirent **eps;
int n;

n = scandir ("./", &eps, one, alphasort);
if (n >= 0)
{
int cnt;
for (cnt = 0; cnt < n; ++cnt)
puts (eps[cnt]->d_name);
}
else
perror ("Couldn't open the directory");

return 0;
}
Please note the simple selector function for this example. Since we want to see all directory entries we always return H1@.
ˆ‰SEC158Št�”›Hard Links

‰IDX761Š‰IDX762Š‰IDX763Š‰IDX764Š
@�”˜In POSIX systems, one file can have many names at the same time. All of the names are equally real, and no one of them is preferred to the others.
To add a name to a file, use the Hlink@ function. (The new name is also called a Bhard link@ to the file.) Creating a new link to a file does not copy the contents of the file; it simply makes a new name by which the file can be known, in addition to the file's existing name or names.
One file can have names in several directories, so the the organization of the file system is not a strict hierarchy or tree.
In most implementations, it is not possible to have hard links to the same file in multiple file systems. Hlink@ reports an error if you try to make a hard link to the file from another file system when this cannot be done.
The prototype for the Hlink@ function is declared in the header file H`unistd.h'@. ‰IDX765Š

A�”˜Function:@ int Dlink@ B(const char *Boldname@, const char *Bnewname@)
Â‰IDX766Š@�”˜The Hlink@ function makes a new link to the existing file named by Boldname@, under the new name Bnewname@.
This function returns a value of H0@ if it is successful and H-1@ on failure. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜) for both Boldname@ and Bnewname@, the following Herrno@ error conditions are defined for this function:
HEACCES
Ä@You are not allowed to write the directory in which the new link is to be written.
ÂHEEXIST
Ä@There is already a file named Bnewname@. If you want to replace this link with a new link, you must remove the old link explicitly first.
ÂHEMLINK
Ä@There are already too many links to the file named by Boldname@. (The maximum number of links to a file is HLINK_MAX@; see section ‰ŠP�”›Limits on File System Capacity@�”˜.)
ÂHENOENT
Ä@The file named by Boldname@ doesn't exist. You can't make a link to a file that doesn't exist.
ÂHENOSPC
Ä@The directory or file system that would contain the new link is full and cannot be extended.
ÂHEPERM
Ä@In the GNU system and some others, you cannot make links to directories. Many systems allow only privileged users to do so. This error is used to report the problem.
ÂHEROFS
Ä@The directory containing the new link can't be modified because it's on a read-only file system.
ÂHEXDEV
Ä@The directory specified in Bnewname@ is on a different file system than the existing file.
ÂHEIO
Ä@A hardware error occurred while trying to read or write the to filesystem.Â
À

ˆ‰SEC159Št�”›Symbolic Links

‰IDX767Š‰IDX768Š‰IDX769Š‰IDX770Š
@�”˜The GNU system supports Bsoft links@ or Bsymbolic links@. This is a kind of "file" that is essentially a pointer to another file name. Unlike hard links, symbolic links can be made to directories or across file systems with no restrictions. You can also make a symbolic link to a name which is not the name of any file. (Opening this link will fail until a file by that name is created.) Likewise, if the symbolic link points to an existing file which is later deleted, the symbolic link continues to point to the same file name even though the name no longer names any file.
The reason symbolic links work the way they do is that special things happen when you try to open the link. The Hopen@ function realizes you have specified the name of a link, reads the file name contained in the link, and opens that file name instead. The Hstat@ function likewise operates on the file that the symbolic link points to, instead of on the link itself.
By contrast, other operations such as deleting or renaming the file operate on the link itself. The functions Hreadlink@ and Hlstat@ also refrain from following symbolic links, because their purpose is to obtain information about the link. So does Hlink@, the function that makes a hard link--it makes a hard link to the symbolic link, which one rarely wants.
Prototypes for the functions listed in this section are in H`unistd.h'@. ‰IDX771Š

A�”˜Function:@ int Dsymlink@ B(const char *Boldname@, const char *Bnewname@)
Â‰IDX772Š@�”˜The Hsymlink@ function makes a symbolic link to Boldname@ named Bnewname@.
The normal return value from Hsymlink@ is H0@. A return value of H-1@ indicates an error. In addition to the usual file name syntax errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEEXIST
Ä@There is already an existing file named Bnewname@.
ÂHEROFS
Ä@The file Bnewname@ would exist on a read-only file system.
ÂHENOSPC
Ä@The directory or file system cannot be extended to make the new link.
ÂHEIO
Ä@A hardware error occurred while reading or writing data on the disk. Â
À

AFunction:@ int Dreadlink@ B(const char *Bfilename@, char *Bbuffer@, size_t Bsize@)
Â‰IDX773Š@�”˜The Hreadlink@ function gets the value of the symbolic link Bfilename@. The file name that the link points to is copied into Bbuffer@. This file name string is Bnot@ null-terminated; Hreadlink@ normally returns the number of characters copied. The Bsize@ argument specifies the maximum number of characters to copy, usually the allocation size of Bbuffer@.
If the return value equals Bsize@, you cannot tell whether or not there was room to return the entire name. So make a bigger buffer and call Hreadlink@ again. Here is an example: char *
readlink_malloc (char *filename)
{
int size = 100;

while (1)
{
char *buffer = (char *) xmalloc (size);
int nchars = readlink (filename, buffer, size);
if (nchars < size)
return buffer;
free (buffer);
size *= 2;
}
}
A value of H-1@ is returned in case of error. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEINVAL
Ä@The named file is not a symbolic link.
ÂHEIO
Ä@A hardware error occurred while reading or writing data on the disk.Â
À

ˆ‰SEC160Št�”›Deleting Files

‰IDX774Š‰IDX775Š‰IDX776Š
@�”˜You can delete a file with the functions Hunlink@ or Hremove@.
Deletion actually deletes a file name. If this is the file's only name, then the file is deleted as well. If the file has other names as well (see section ‰ŠP�”›Hard Links@�”˜), it remains accessible under its other names.

AFunction:@ int Dunlink@ B(const char *Bfilename@)
Â‰IDX777Š@�”˜The Hunlink@ function deletes the file name Bfilename@. If this is a file's sole name, the file itself is also deleted. (Actually, if any process has the file open when this happens, deletion is postponed until all processes have closed the file.)
‰IDX778Š@�”˜The function Hunlink@ is declared in the header file H`unistd.h'@.
This function returns H0@ on successful completion, and H-1@ on error. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEACCES
Ä@Write permission is denied for the directory from which the file is to be removed, or the directory has the sticky bit set and you do not own the file.
ÂHEBUSY
Ä@This error indicates that the file is being used by the system in such a way that it can't be unlinked. For example, you might see this error if the file name specifies the root directory or a mount point for a file system.
ÂHENOENT
Ä@The file name to be deleted doesn't exist.
ÂHEPERM
Ä@On some systems, Hunlink@ cannot be used to delete the name of a directory, or can only be used this way by a privileged user. To avoid such problems, use Hrmdir@ to delete directories. (In the GNU system Hunlink@ can never delete the name of a directory.)
ÂHEROFS
Ä@The directory in which the file name is to be deleted is on a read-only file system, and can't be modified.Â
À

AFunction:@ int Drmdir@ B(const char *Bfilename@)
Â‰IDX779Š‰IDX780Š‰IDX781Š@�”˜The Hrmdir@ function deletes a directory. The directory must be empty before it can be removed; in other words, it can only contain entries for H`.'@ and H`..'@.
In most other respects, Hrmdir@ behaves like Hunlink@. There are two additional Herrno@ error conditions defined for Hrmdir@:
HENOTEMPTY
Ä
ÂHEEXIST
Ä@The directory to be deleted is not empty.Â

These two error codes are synonymous; some systems use one, and some use the other. The GNU system always uses HENOTEMPTY@.
The prototype for this function is declared in the header file H`unistd.h'@. ‰IDX782ŠÀ

A�”˜Function:@ int Dremove@ B(const char *Bfilename@)
Â‰IDX783Š@�”˜This is the ISO C function to remove a file. It works like Hunlink@ for files and like Hrmdir@ for directories. Hremove@ is declared in H`stdio.h'@. ‰IDX784ŠÀ

ˆ‰SEC161Št�”›Renaming Files

@�”˜The Hrename@ function is used to change a file's name.
‰IDX785Š
A�”˜Function:@ int Drename@ B(const char *Boldname@, const char *Bnewname@)
Â‰IDX786Š@�”˜The Hrename@ function renames the file name Boldname@ with Bnewname@. The file formerly accessible under the name Boldname@ is afterward accessible as Bnewname@ instead. (If the file had any other names aside from Boldname@, it continues to have those names.)
The directory containing the name Bnewname@ must be on the same file system as the file (as indicated by the name Boldname@).
One special case for Hrename@ is when Boldname@ and Bnewname@ are two names for the same file. The consistent way to handle this case is to delete Boldname@. However, POSIX requires that in this case Hrename@ do nothing and report success--which is inconsistent. We don't know what your operating system will do.
If the Boldname@ is not a directory, then any existing file named Bnewname@ is removed during the renaming operation. However, if Bnewname@ is the name of a directory, Hrename@ fails in this case.
If the Boldname@ is a directory, then either Bnewname@ must not exist or it must name a directory that is empty. In the latter case, the existing directory named Bnewname@ is deleted first. The name Bnewname@ must not specify a subdirectory of the directory Holdname@ which is being renamed.
One useful feature of Hrename@ is that the meaning of the name Bnewname@ changes "atomically" from any previously existing file by that name to its new meaning (the file that was called Boldname@). There is no instant at which Bnewname@ is nonexistent "in between" the old meaning and the new meaning. If there is a system crash during the operation, it is possible for both names to still exist; but Bnewname@ will always be intact if it exists at all.
If Hrename@ fails, it returns H-1@. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEACCES
Ä@One of the directories containing Bnewname@ or Boldname@ refuses write permission; or Bnewname@ and Boldname@ are directories and write permission is refused for one of them.
ÂHEBUSY
Ä@A directory named by Boldname@ or Bnewname@ is being used by the system in a way that prevents the renaming from working. This includes directories that are mount points for filesystems, and directories that are the current working directories of processes.
ÂHENOTEMPTY
Ä
ÂHEEXIST
Ä@The directory Bnewname@ isn't empty. The GNU system always returns HENOTEMPTY@ for this, but some other systems return HEEXIST@.
ÂHEINVAL
Ä@The Boldname@ is a directory that contains Bnewname@.
ÂHEISDIR
Ä@The Bnewname@ names a directory, but the Boldname@ doesn't.
ÂHEMLINK
Ä@The parent directory of Bnewname@ would have too many links.
ÂHENOENT
Ä@The file named by Boldname@ doesn't exist.
ÂHENOSPC
Ä@The directory that would contain Bnewname@ has no room for another entry, and there is no space left in the file system to expand it.
ÂHEROFS
Ä@The operation would involve writing to a directory on a read-only file system.
ÂHEXDEV
Ä@The two file names Bnewname@ and Boldnames@ are on different file systems.Â
À

ˆ‰SEC162Št�”›Creating Directories

‰IDX787Š‰IDX788Š
‰IDX789Š@�”˜Directories are created with the Hmkdir@ function. (There is also a shell command Hmkdir@ which does the same thing.)

AFunction:@ int Dmkdir@ B(const char *Bfilename@, mode_t Bmode@)
Â‰IDX790Š@�”˜The Hmkdir@ function creates a new, empty directory whose name is Bfilename@.
The argument Bmode@ specifies the file permissions for the new directory file. See section ‰ŠP�”›The Mode Bits for Access Permission@�”˜, for more information about this.
A return value of H0@ indicates successful completion, and H-1@ indicates failure. In addition to the usual file name syntax errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEACCES
Ä@Write permission is denied for the parent directory in which the new directory is to be added.
ÂHEEXIST
Ä@A file named Bfilename@ already exists.
ÂHEMLINK
Ä@The parent directory has too many links. Well-designed file systems never report this error, because they permit more links than your disk could possibly hold. However, you must still take account of the possibility of this error, as it could result from network access to a file system on another machine.
ÂHENOSPC
Ä@The file system doesn't have enough room to create the new directory.
ÂHEROFS
Ä@The parent directory of the directory being created is on a read-only file system, and cannot be modified.Â

To use this function, your program should include the header file H`sys/stat.h'@. ‰IDX791ŠÀ

ˆ‰SEC163Št�”›File Attributes

‰IDX792Š@�”˜When you issue an H`ls -l'@ shell command on a file, it gives you information about the size of the file, who owns it, when it was last modified, and the like. This kind of information is called the Bfile attributes@; it is associated with the file itself and not a particular one of its names.
This section contains information about how you can inquire about and modify these attributes of files.
ˆ‰SEC164ŠT�”›What the File Attribute Values Mean

‰IDX793Š‰IDX794Š‰IDX795Š
@�”˜When you read the attributes of a file, they come back in a structure called Hstruct stat@. This section describes the names of the attributes, their data types, and what they mean. For the functions to read the attributes of a file, see section ‰ŠP�”›Reading the Attributes of a File@�”˜.
The header file H`sys/stat.h'@ declares all the symbols defined in this section. ‰IDX796Š

A�”˜Data Type:@ Dstruct stat
Â‰IDX797Š@�”˜The Hstat@ structure type is used to return information about the attributes of a file. It contains at least the following members:
Hmode_t st_mode
Ä@Specifies the mode of the file. This includes file type information (see section ‰ŠP�”›Testing the Type of a File@�”˜) and the file permission bits (see section ‰ŠP�”›The Mode Bits for Access Permission@�”˜).
ÂHino_t st_ino
Ä@The file serial number, which distinguishes this file from all other files on the same device.
ÂHdev_t st_dev
Ä@Identifies the device containing the file. The Hst_ino@ and Hst_dev@, taken together, uniquely identify the file. The Hst_dev@ value is not necessarily consistent across reboots or system crashes, however.
ÂHnlink_t st_nlink
Ä@The number of hard links to the file. This count keeps track of how many directories have entries for this file. If the count is ever decremented to zero, then the file itself is discarded as soon as no process still holds it open. Symbolic links are not counted in the total.
ÂHuid_t st_uid
Ä@The user ID of the file's owner. See section ‰ŠP�”›File Owner@�”˜.
ÂHgid_t st_gid
Ä@The group ID of the file. See section ‰ŠP�”›File Owner@�”˜.
ÂHoff_t st_size
Ä@This specifies the size of a regular file in bytes. For files that are really devices and the like, this field isn't usually meaningful. For symbolic links, this specifies the length of the file name the link refers to.
ÂHtime_t st_atime
Ä@This is the last access time for the file. See section ‰ŠP�”›File Times@�”˜.
ÂHunsigned long int st_atime_usec
Ä@This is the fractional part of the last access time for the file. See section ‰ŠP�”›File Times@�”˜.
ÂHtime_t st_mtime
Ä@This is the time of the last modification to the contents of the file. See section ‰ŠP�”›File Times@�”˜.
ÂHunsigned long int st_mtime_usec
Ä@This is the fractional part of the time of last modification to the contents of the file. See section ‰ŠP�”›File Times@�”˜.
ÂHtime_t st_ctime
Ä@This is the time of the last modification to the attributes of the file. See section ‰ŠP�”›File Times@�”˜.
ÂHunsigned long int st_ctime_usec
Ä@This is the fractional part of the time of last modification to the attributes of the file. See section ‰ŠP�”›File Times@�”˜.
ÂHunsigned int st_blocks
Ä@This is the amount of disk space that the file occupies, measured in units of 512-byte blocks. The number of disk blocks is not strictly proportional to the size of the file, for two reasons: the file system may use some blocks for internal record keeping; and the file may be sparse--it may have "holes" which contain zeros but do not actually take up space on the disk. You can tell (approximately) whether a file is sparse by comparing this value with Hst_size@, like this: (st.st_blocks * 512 < st.st_size) This test is not perfect because a file that is just slightly sparse might not be detected as sparse at all. For practical applications, this is not a problem.
ÂHunsigned int st_blksize
Ä@The optimal block size for reading of writing this file, in bytes. You might use this size for allocating the buffer space for reading of writing the file. (This is unrelated to Hst_blocks@.)Â
À

Some of the file attributes have special data type names which exist specifically for those attributes. (They are all aliases for well-known integer types that you know and love.) These typedef names are defined in the header file H`sys/types.h'@ as well as in H`sys/stat.h'@. Here is a list of them.

AData Type:@ Dmode_t
Â‰IDX798Š@�”˜This is an integer data type used to represent file modes. In the GNU system, this is equivalent to Hunsigned int@.À

‰IDX799Š
A�”˜Data Type:@ Dino_t
Â‰IDX800Š@�”˜This is an arithmetic data type used to represent file serial numbers. (In Unix jargon, these are sometimes called Binode numbers@.) In the GNU system, this type is equivalent to Hunsigned long int@.À

AData Type:@ Ddev_t
Â‰IDX801Š@�”˜This is an arithmetic data type used to represent file device numbers. In the GNU system, this is equivalent to Hint@.À

AData Type:@ Dnlink_t
Â‰IDX802Š@�”˜This is an arithmetic data type used to represent file link counts. In the GNU system, this is equivalent to Hunsigned short int@.À

ˆ‰SEC165ŠT�”›Reading the Attributes of a File

@�”˜To examine the attributes of files, use the functions Hstat@, Hfstat@ and Hlstat@. They return the attribute information in a Hstruct stat@ object. All three functions are declared in the header file H`sys/stat.h'@.

AFunction:@ int Dstat@ B(const char *Bfilename@, struct stat *Bbuf@)
Â‰IDX803Š@�”˜The Hstat@ function returns information about the attributes of the file named by Bfilename@ in the structure pointed at by Bbuf@.
If Bfilename@ is the name of a symbolic link, the attributes you get describe the file that the link points to. If the link points to a nonexistent file name, then Hstat@ fails, reporting a nonexistent file.
The return value is H0@ if the operation is successful, and H-1@ on failure. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜, the following Herrno@ error conditions are defined for this function:
HENOENT
Ä@The file named by Bfilename@ doesn't exist.Â
À

AFunction:@ int Dfstat@ B(int Bfiledes@, struct stat *Bbuf@)
Â‰IDX804Š@�”˜The Hfstat@ function is like Hstat@, except that it takes an open file descriptor as an argument instead of a file name. See section ‰ŠP�”›Low-Level Input/Output@�”˜.
Like Hstat@, Hfstat@ returns H0@ on success and H-1@ on failure. The following Herrno@ error conditions are defined for Hfstat@:
HEBADF
Ä@The Bfiledes@ argument is not a valid file descriptor.Â
À

AFunction:@ int Dlstat@ B(const char *Bfilename@, struct stat *Bbuf@)
Â‰IDX805Š@�”˜The Hlstat@ function is like Hstat@, except that it does not follow symbolic links. If Bfilename@ is the name of a symbolic link, Hlstat@ returns information about the link itself; otherwise, Hlstat@ works like Hstat@. See section ‰ŠP�”›Symbolic Links@�”˜.À

ˆ‰SEC166ŠT�”›Testing the Type of a File

@�”˜The Bfile mode@, stored in the Hst_mode@ field of the file attributes, contains two kinds of information: the file type code, and the access permission bits. This section discusses only the type code, which you can use to tell whether the file is a directory, whether it is a socket, and so on. For information about the access permission, section ‰ŠP�”›The Mode Bits for Access Permission@�”˜.
There are two predefined ways you can access the file type portion of the file mode. First of all, for each type of file, there is a Bpredicate macro@ which examines a file mode value and returns true or false--is the file of that type, or not. Secondly, you can mask out the rest of the file mode to get just a file type code. You can compare this against various constants for the supported file types.
All of the symbols listed in this section are defined in the header file H`sys/stat.h'@. ‰IDX806Š
@�”˜The following predicate macros test the type of a file, given the value Bm@ which is the Hst_mode@ field returned by Hstat@ on that file:

AMacro:@ int DS_ISDIR@ B(mode_t Bm@)
Â‰IDX807Š@�”˜This macro returns nonzero if the file is a directory.À

AMacro:@ int DS_ISCHR@ B(mode_t Bm@)
Â‰IDX808Š@�”˜This macro returns nonzero if the file is a character special file (a device like a terminal).À

AMacro:@ int DS_ISBLK@ B(mode_t Bm@)
Â‰IDX809Š@�”˜This macro returns nonzero if the file is a block special file (a device like a disk).À

AMacro:@ int DS_ISREG@ B(mode_t Bm@)
Â‰IDX810Š@�”˜This macro returns nonzero if the file is a regular file.À

AMacro:@ int DS_ISFIFO@ B(mode_t Bm@)
Â‰IDX811Š@�”˜This macro returns nonzero if the file is a FIFO special file, or a pipe. See section ‰ŠP�”›Pipes and FIFOs@�”˜.À

AMacro:@ int DS_ISLNK@ B(mode_t Bm@)
Â‰IDX812Š@�”˜This macro returns nonzero if the file is a symbolic link. See section ‰ŠP�”›Symbolic Links@�”˜.À

AMacro:@ int DS_ISSOCK@ B(mode_t Bm@)
Â‰IDX813Š@�”˜This macro returns nonzero if the file is a socket. See section ‰ŠP�”›Sockets@�”˜.À

An alterate non-POSIX method of testing the file type is supported for compatibility with BSD. The mode can be bitwise ANDed with HS_IFMT@ to extract the file type code, and compared to the appropriate type code constant. For example, S_ISCHR (Bmode@)
is equivalent to: ((Bmode@ & S_IFMT) == S_IFCHR)

AMacro:@ int DS_IFMT
Â‰IDX814Š@�”˜This is a bit mask used to extract the file type code portion of a mode value.À

These are the symbolic names for the different file type codes:
HS_IFDIR
Â‰IDX815Š@�”˜This macro represents the value of the file type code for a directory file.
ÀHS_IFCHR
Â‰IDX816Š@�”˜This macro represents the value of the file type code for a character-oriented device file.
ÀHS_IFBLK
Â‰IDX817Š@�”˜This macro represents the value of the file type code for a block-oriented device file.
ÀHS_IFREG
Â‰IDX818Š@�”˜This macro represents the value of the file type code for a regular file.
ÀHS_IFLNK
Â‰IDX819Š@�”˜This macro represents the value of the file type code for a symbolic link.
ÀHS_IFSOCK
Â‰IDX820Š@�”˜This macro represents the value of the file type code for a socket.
ÀHS_IFIFO
Â‰IDX821Š@�”˜This macro represents the value of the file type code for a FIFO or pipe.À

ˆ‰SEC167ŠT�”›File Owner

‰IDX822Š‰IDX823Š‰IDX824Š
@�”˜Every file has an Bowner@ which is one of the registered user names defined on the system. Each file also has a Bgroup@, which is one of the defined groups. The file owner can often be useful for showing you who edited the file (especially when you edit with GNU Emacs), but its main purpose is for access control.
The file owner and group play a role in determining access because the file has one set of access permission bits for the user that is the owner, another set that apply to users who belong to the file's group, and a third set of bits that apply to everyone else. See section ‰ŠP�”›How Your Access to a File is Decided@�”˜, for the details of how access is decided based on this data.
When a file is created, its owner is set from the effective user ID of the process that creates it (see section ‰ŠP�”›The Persona of a Process@�”˜). The file's group ID may be set from either effective group ID of the process, or the group ID of the directory that contains the file, depending on the system where the file is stored. When you access a remote file system, it behaves according to its own rule, not according to the system your program is running on. Thus, your program must be prepared to encounter either kind of behavior, no matter what kind of system you run it on.
‰IDX825Š‰IDX826Š@�”˜You can change the owner and/or group owner of an existing file using the Hchown@ function. This is the primitive for the Hchown@ and Hchgrp@ shell commands.
‰IDX827Š@�”˜The prototype for this function is declared in H`unistd.h'@.

AFunction:@ int Dchown@ B(const char *Bfilename@, uid_t Bowner@, gid_t Bgroup@)
Â‰IDX828Š@�”˜The Hchown@ function changes the owner of the file Bfilename@ to Bowner@, and its group owner to Bgroup@.
Changing the owner of the file on certain systems clears the set-user-ID and set-group-ID bits of the file's permissions. (This is because those bits may not be appropriate for the new owner.) The other file permission bits are not changed.
The return value is H0@ on success and H-1@ on failure. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEPERM
Ä@This process lacks permission to make the requested change. Only privileged users or the file's owner can change the file's group. On most file systems, only privileged users can change the file owner; some file systems allow you to change the owner if you are currently the owner. When you access a remote file system, the behavior you encounter is determined by the system that actually holds the file, not by the system your program is running on. See section ‰ŠP�”›Optional Features in File Support@�”˜, for information about the H_POSIX_CHOWN_RESTRICTED@ macro.
ÂHEROFS
Ä@The file is on a read-only file system.Â
À

AFunction:@ int Dfchown@ B(int Bfiledes@, int Bowner@, int Bgroup@)
Â‰IDX829Š@�”˜This is like Hchown@, except that it changes the owner of the file with open file descriptor Bfiledes@.
The return value from Hfchown@ is H0@ on success and H-1@ on failure. The following Herrno@ error codes are defined for this function:
HEBADF
Ä@The Bfiledes@ argument is not a valid file descriptor.
ÂHEINVAL
Ä@The Bfiledes@ argument corresponds to a pipe or socket, not an ordinary file.
ÂHEPERM
Ä@This process lacks permission to make the requested change. For details, see Hchmod@, above.
ÂHEROFS
Ä@The file resides on a read-only file system.Â
À

ˆ‰SEC168ŠT�”›The Mode Bits for Access Permission

@�”˜The Bfile mode@, stored in the Hst_mode@ field of the file attributes, contains two kinds of information: the file type code, and the access permission bits. This section discusses only the access permission bits, which control who can read or write the file. See section ‰ŠP�”›Testing the Type of a File@�”˜, for information about the file type code.
All of the symbols listed in this section are defined in the header file H`sys/stat.h'@. ‰IDX830Š
‰IDX831Š@�”˜These symbolic constants are defined for the file mode bits that control access permission for the file:
HS_IRUSR
Â‰IDX832Š
ÀH�”˜S_IREAD
Â‰IDX833Š@�”˜Read permission bit for the owner of the file. On many systems, this bit is 0400. HS_IREAD@ is an obsolete synonym provided for BSD compatibility.
ÀHS_IWUSR
Â‰IDX834Š
ÀH�”˜S_IWRITE
Â‰IDX835Š@�”˜Write permission bit for the owner of the file. Usually 0200. HS_IWRITE@ is an obsolete synonym provided for BSD compatibility.
ÀHS_IXUSR
Â‰IDX836Š
ÀH�”˜S_IEXEC
Â‰IDX837Š@�”˜Execute (for ordinary files) or search (for directories) permission bit for the owner of the file. Usually 0100. HS_IEXEC@ is an obsolete synonym provided for BSD compatibility.
ÀHS_IRWXU
Â‰IDX838Š@�”˜This is equivalent to H`(S_IRUSR | S_IWUSR | S_IXUSR)'@.
ÀHS_IRGRP
Â‰IDX839Š@�”˜Read permission bit for the group owner of the file. Usually 040.
ÀHS_IWGRP
Â‰IDX840Š@�”˜Write permission bit for the group owner of the file. Usually 020.
ÀHS_IXGRP
Â‰IDX841Š@�”˜Execute or search permission bit for the group owner of the file. Usually 010.
ÀHS_IRWXG
Â‰IDX842Š@�”˜This is equivalent to H`(S_IRGRP | S_IWGRP | S_IXGRP)'@.
ÀHS_IROTH
Â‰IDX843Š@�”˜Read permission bit for other users. Usually 04.
ÀHS_IWOTH
Â‰IDX844Š@�”˜Write permission bit for other users. Usually 02.
ÀHS_IXOTH
Â‰IDX845Š@�”˜Execute or search permission bit for other users. Usually 01.
ÀHS_IRWXO
Â‰IDX846Š@�”˜This is equivalent to H`(S_IROTH | S_IWOTH | S_IXOTH)'@.
ÀHS_ISUID
Â‰IDX847Š@�”˜This is the set-user-ID on execute bit, usually 04000. See section ‰ŠP�”›How an Application Can Change Persona@�”˜.
ÀHS_ISGID
Â‰IDX848Š@�”˜This is the set-group-ID on execute bit, usually 02000. See section ‰ŠP�”›How an Application Can Change Persona@�”˜. ‰IDX849Š
ÀH�”˜S_ISVTX
Â‰IDX850Š@�”˜This is the Bsticky@ bit, usually 01000. On a directory, it gives permission to delete a file in the directory only if you own that file. Ordinarily, a user either can delete all the files in the directory or cannot delete any of them (based on whether the user has write permission for the directory). The same restriction applies--you must both have write permission for the directory and own the file you want to delete. The one exception is that the owner of the directory can delete any file in the directory, no matter who owns it (provided the owner has given himself write permission for the directory). This is commonly used for the H`/tmp'@ directory, where anyone may create files, but not delete files created by other users. Originally the sticky bit on an executable file modified the swapping policies of the system. Normally, when a program terminated, its pages in core were immediately freed and reused. If the sticky bit was set on the executable file, the system kept the pages in core for a while as if the program were still running. This was advantageous for a program likely to be run many times in succession. This usage is obsolete in modern systems. When a program terminates, its pages always remain in core as long as there is no shortage of memory in the system. When the program is next run, its pages will still be in core if no shortage arose since the last run. On some modern systems where the sticky bit has no useful meaning for an executable file, you cannot set the bit at all for a non-directory. If you try, Hchmod@ fails with HEFTYPE@; see section ‰ŠP�”›Assigning File Permissions@�”˜. Some systems (particularly SunOS) have yet another use for the sticky bit. If the sticky bit is set on a file that is Bnot@ executable, it means the opposite: never cache the pages of this file at all. The main use of this is for the files on an NFS server machine which are used as the swap area of diskless client machines. The idea is that the pages of the file will be cached in the client's memory, so it is a waste of the server's memory to cache them a second time. In this use the sticky bit also says that the filesystem may fail to record the file's modification time onto disk reliably (the idea being that noone cares for a swap file).À

The actual bit values of the symbols are listed in the table above so you can decode file mode values when debugging your programs. These bit values are correct for most systems, but they are not guaranteed.
DWarning:@ Writing explicit numbers for file permissions is bad practice. It is not only nonportable, it also requires everyone who reads your program to remember what the bits mean. To make your program clean, use the symbolic names.
ˆ‰SEC169ŠT�”›How Your Access to a File is Decided

‰IDX851Š‰IDX852Š‰IDX853Š
@�”˜Recall that the operating system normally decides access permission for a file based on the effective user and group IDs of the process, and its supplementary group IDs, together with the file's owner, group and permission bits. These concepts are discussed in detail in section ‰ŠP�”›The Persona of a Process@�”˜.
If the effective user ID of the process matches the owner user ID of the file, then permissions for read, write, and execute/search are controlled by the corresponding "user" (or "owner") bits. Likewise, if any of the effective group ID or supplementary group IDs of the process matches the group owner ID of the file, then permissions are controlled by the "group" bits. Otherwise, permissions are controlled by the "other" bits.
Privileged users, like H`root'@, can access any file, regardless of its file permission bits. As a special case, for a file to be executable even for a privileged user, at least one of its execute bits must be set.
ˆ‰SEC170ŠT�”›Assigning File Permissions

‰IDX854Š‰IDX855Š@�”˜The primitive functions for creating files (for example, Hopen@ or Hmkdir@) take a Bmode@ argument, which specifies the file permissions for the newly created file. But the specified mode is modified by the process's Bfile creation mask@, or Bumask@, before it is used.
The bits that are set in the file creation mask identify permissions that are always to be disabled for newly created files. For example, if you set all the "other" access bits in the mask, then newly created files are not accessible at all to processes in the "other" category, even if the Bmode@ argument specified to the creation function would permit such access. In other words, the file creation mask is the complement of the ordinary access permissions you want to grant.
Programs that create files typically specify a Bmode@ argument that includes all the permissions that make sense for the particular file. For an ordinary file, this is typically read and write permission for all classes of users. These permissions are then restricted as specified by the individual user's own file creation mask.
‰IDX856Š@�”˜To change the permission of an existing file given its name, call Hchmod@. This function ignores the file creation mask; it uses exactly the specified permission bits.
‰IDX857Š@�”˜In normal use, the file creation mask is initialized in the user's login shell (using the Humask@ shell command), and inherited by all subprocesses. Application programs normally don't need to worry about the file creation mask. It will do automatically what it is supposed to do.
When your program should create a file and bypass the umask for its access permissions, the easiest way to do this is to use Hfchmod@ after opening the file, rather than changing the umask.
In fact, changing the umask is usually done only by shells. They use the Humask@ function.
The functions in this section are declared in H`sys/stat.h'@. ‰IDX858Š

A�”˜Function:@ mode_t Dumask@ B(mode_t Bmask@)
Â‰IDX859Š@�”˜The Humask@ function sets the file creation mask of the current process to Bmask@, and returns the previous value of the file creation mask.
Here is an example showing how to read the mask with Humask@ without changing it permanently: mode_t
read_umask (void)
{
mask = umask (0);
umask (mask);
}
However, it is better to use Hgetumask@ if you just want to read the mask value, because that is reentrant (at least if you use the GNU operating system).À

AFunction:@ mode_t Dgetumask@ B(void)
Â‰IDX860Š@�”˜Return the current value of the file creation mask for the current process. This function is a GNU extension.À

AFunction:@ int Dchmod@ B(const char *Bfilename@, mode_t Bmode@)
Â‰IDX861Š@�”˜The Hchmod@ function sets the access permission bits for the file named by Bfilename@ to Bmode@.
If the Bfilename@ names a symbolic link, Hchmod@ changes the permission of the file pointed to by the link, not those of the link itself.
This function returns H0@ if successful and H-1@ if not. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HENOENT
Ä@The named file doesn't exist.
ÂHEPERM
Ä@This process does not have permission to change the access permission of this file. Only the file's owner (as judged by the effective user ID of the process) or a privileged user can change them.
ÂHEROFS
Ä@The file resides on a read-only file system.
ÂHEFTYPE
ÄBmode@ has the HS_ISVTX@ bit (the "sticky bit") set, and the named file is not a directory. Some systems do not allow setting the sticky bit on non-directory files, and some do (and only some of those assign a useful meaning to the bit for non-directory files). You only get HEFTYPE@ on systems where the sticky bit has no useful meaning for non-directory files, so it is always safe to just clear the bit in Bmode@ and call Hchmod@ again. See section ‰ŠP�”›The Mode Bits for Access Permission@�”˜, for full details on the sticky bit.Â
À

AFunction:@ int Dfchmod@ B(int Bfiledes@, int Bmode@)
Â‰IDX862Š@�”˜This is like Hchmod@, except that it changes the permissions of the file currently open via descriptor Bfiledes@.
The return value from Hfchmod@ is H0@ on success and H-1@ on failure. The following Herrno@ error codes are defined for this function:
HEBADF
Ä@The Bfiledes@ argument is not a valid file descriptor.
ÂHEINVAL
Ä@The Bfiledes@ argument corresponds to a pipe or socket, or something else that doesn't really have access permissions.
ÂHEPERM
Ä@This process does not have permission to change the access permission of this file. Only the file's owner (as judged by the effective user ID of the process) or a privileged user can change them.
ÂHEROFS
Ä@The file resides on a read-only file system.Â
À

ˆ‰SEC171ŠT�”›Testing Permission to Access a File

‰IDX863Š‰IDX864Š‰IDX865Š
@�”˜When a program runs as a privileged user, this permits it to access files off-limits to ordinary users--for example, to modify H`/etc/passwd'@. Programs designed to be run by ordinary users but access such files use the setuid bit feature so that they always run with Hroot@ as the effective user ID.
Such a program may also access files specified by the user, files which conceptually are being accessed explicitly by the user. Since the program runs as Hroot@, it has permission to access whatever file the user specifies--but usually the desired behavior is to permit only those files which the user could ordinarily access.
The program therefore must explicitly check whether Bthe user@ would have the necessary access to a file, before it reads or writes the file.
To do this, use the function Haccess@, which checks for access permission based on the process's Breal@ user ID rather than the effective user ID. (The setuid feature does not alter the real user ID, so it reflects the user who actually ran the program.)
There is another way you could check this access, which is easy to describe, but very hard to use. This is to examine the file mode bits and mimic the system's own access computation. This method is undesirable because many systems have additional access control features; your program cannot portably mimic them, and you would not want to try to keep track of the diverse features that different systems have. Using Haccess@ is simple and automatically does whatever is appropriate for the system you are using.
Haccess@ is Bonly@ only appropriate to use in setuid programs. A non-setuid program will always use the effective ID rather than the real ID.
‰IDX866Š@�”˜The symbols in this section are declared in H`unistd.h'@.

AFunction:@ int Daccess@ B(const char *Bfilename@, int Bhow@)
Â‰IDX867Š@�”˜The Haccess@ function checks to see whether the file named by Bfilename@ can be accessed in the way specified by the Bhow@ argument. The Bhow@ argument either can be the bitwise OR of the flags HR_OK@, HW_OK@, HX_OK@, or the existence test HF_OK@.
This function uses the Breal@ user and group ID's of the calling process, rather than the Beffective@ ID's, to check for access permission. As a result, if you use the function from a Hsetuid@ or Hsetgid@ program (see section ‰ŠP�”›How an Application Can Change Persona@�”˜), it gives information relative to the user who actually ran the program.
The return value is H0@ if the access is permitted, and H-1@ otherwise. (In other words, treated as a predicate function, Haccess@ returns true if the requested access is Bdenied@.)
In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEACCES
Ä@The access specified by Bhow@ is denied.
ÂHENOENT
Ä@The file doesn't exist.
ÂHEROFS
Ä@Write permission was requested for a file on a read-only file system.Â
À

These macros are defined in the header file H`unistd.h'@ for use as the Bhow@ argument to the Haccess@ function. The values are integer constants. ‰IDX868Š

A�”˜Macro:@ int DR_OK
Â‰IDX869Š@�”˜Argument that means, test for read permission.À

AMacro:@ int DW_OK
Â‰IDX870Š@�”˜Argument that means, test for write permission.À

AMacro:@ int DX_OK
Â‰IDX871Š@�”˜Argument that means, test for execute/search permission.À

AMacro:@ int DF_OK
Â‰IDX872Š@�”˜Argument that means, test for existence of the file.À

ˆ‰SEC172ŠT�”›File Times

‰IDX873Š‰IDX874Š‰IDX875Š@�”˜Each file has three timestamps associated with it: its access time, its modification time, and its attribute modification time. These correspond to the Hst_atime@, Hst_mtime@, and Hst_ctime@ members of the Hstat@ structure; see section ‰ŠP�”›File Attributes@�”˜.
All of these times are represented in calendar time format, as Htime_t@ objects. This data type is defined in H`time.h'@. For more information about representation and manipulation of time values, see section ‰ŠP�”›Calendar Time@�”˜. ‰IDX876Š
@�”˜Reading from a file updates its access time attribute, and writing updates its modification time. When a file is created, all three timestamps for that file are set to the current time. In addition, the attribute change time and modification time fields of the directory that contains the new entry are updated.
Adding a new name for a file with the Hlink@ function updates the attribute change time field of the file being linked, and both the attribute change time and modification time fields of the directory containing the new name. These same fields are affected if a file name is deleted with Hunlink@, Hremove@, or Hrmdir@. Renaming a file with Hrename@ affects only the attribute change time and modification time fields of the two parent directories involved, and not the times for the file being renamed.
Changing attributes of a file (for example, with Hchmod@) updates its attribute change time field.
You can also change some of the timestamps of a file explicitly using the Hutime@ function--all except the attribute change time. You need to include the header file H`utime.h'@ to use this facility. ‰IDX877Š

A�”˜Data Type:@ Dstruct utimbuf
Â‰IDX878Š@�”˜The Hutimbuf@ structure is used with the Hutime@ function to specify new access and modification times for a file. It contains the following members:
Htime_t actime
Ä@This is the access time for the file.
ÂHtime_t modtime
Ä@This is the modification time for the file.Â
À

AFunction:@ int Dutime@ B(const char *Bfilename@, const struct utimbuf *Btimes@)
Â‰IDX879Š@�”˜This function is used to modify the file times associated with the file named Bfilename@.
If Btimes@ is a null pointer, then the access and modification times of the file are set to the current time. Otherwise, they are set to the values from the Hactime@ and Hmodtime@ members (respectively) of the Hutimbuf@ structure pointed at by Btimes@.
The attribute modification time for the file is set to the current time in either case (since changing the timestamps is itself a modification of the file attributes).
The Hutime@ function returns H0@ if successful and H-1@ on failure. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEACCES
Ä@There is a permission problem in the case where a null pointer was passed as the Btimes@ argument. In order to update the timestamp on the file, you must either be the owner of the file, have write permission on the file, or be a privileged user.
ÂHENOENT
Ä@The file doesn't exist.
ÂHEPERM
Ä@If the Btimes@ argument is not a null pointer, you must either be the owner of the file or be a privileged user. This error is used to report the problem.
ÂHEROFS
Ä@The file lives on a read-only file system.Â
À

Each of the three time stamps has a corresponding microsecond part, which extends its resolution. These fields are called Hst_atime_usec@, Hst_mtime_usec@, and Hst_ctime_usec@; each has a value between 0 and 999,999, which indicates the time in microseconds. They correspond to the Htv_usec@ field of a Htimeval@ structure; see section ‰ŠP�”›High-Resolution Calendar@�”˜.
The Hutimes@ function is like Hutime@, but also lets you specify the fractional part of the file times. The prototype for this function is in the header file H`sys/time.h'@. ‰IDX880Š

A�”˜Function:@ int Dutimes@ B(const char *Bfilename@, struct timeval BtvpH[2]@)
Â‰IDX881Š@�”˜This function sets the file access and modification times for the file named by Bfilename@. The new file access time is specified by JtvpH[0]@, and the new modification time by JtvpH[1]@. This function comes from BSD.
The return values and error conditions are the same as for the Hutime@ function.À

ˆ‰SEC173Št�”›Making Special Files

‰IDX882Š‰IDX883Š
@�”˜The Hmknod@ function is the primitive for making special files, such as files that correspond to devices. The GNU library includes this function for compatibility with BSD.
The prototype for Hmknod@ is declared in H`sys/stat.h'@. ‰IDX884Š

A�”˜Function:@ int Dmknod@ B(const char *Bfilename@, int Bmode@, int Bdev@)
Â‰IDX885Š@�”˜The Hmknod@ function makes a special file with name Bfilename@. The Bmode@ specifies the mode of the file, and may include the various special file bits, such as HS_IFCHR@ (for a character special file) or HS_IFBLK@ (for a block special file). See section ‰ŠP�”›Testing the Type of a File@�”˜.
The Bdev@ argument specifies which device the special file refers to. Its exact interpretation depends on the kind of special file being created.
The return value is H0@ on success and H-1@ on error. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for this function:
HEPERM
Ä@The calling process is not privileged. Only the superuser can create special files.
ÂHENOSPC
Ä@The directory or file system that would contain the new file is full and cannot be extended.
ÂHEROFS
Ä@The directory containing the new file can't be modified because it's on a read-only file system.
ÂHEEXIST
Ä@There is already a file named Bfilename@. If you want to replace this file, you must remove the old file explicitly first.Â
À

ˆ‰SEC174Št�”›Temporary Files

@�”˜If you need to use a temporary file in your program, you can use the Htmpfile@ function to open it. Or you can use the Htmpnam@ (better: Htmpnam_r@) function make a name for a temporary file and then open it in the usual way with Hfopen@.
The Htempnam@ function is like Htmpnam@ but lets you choose what directory temporary files will go in, and something about what their file names will look like. Important for multi threaded programs is that Htempnam@ is reentrant while Htmpnam@ is not since it returns a pointer to a static buffer.
These facilities are declared in the header file H`stdio.h'@. ‰IDX886Š

A�”˜Function:@ FILE * Dtmpfile@ B(void)
Â‰IDX887Š@�”˜This function creates a temporary binary file for update mode, as if by calling Hfopen@ with mode H"wb+"@. The file is deleted automatically when it is closed or when the program terminates. (On some other ISO C systems the file may fail to be deleted if the program terminates abnormally).
This function is reentrant.À

AFunction:@ char * Dtmpnam@ B(char *Bresult@)
Â‰IDX888Š@�”˜This function constructs and returns a file name that is a valid file name and that does not name any existing file. If the Bresult@ argument is a null pointer, the return value is a pointer to an internal static string, which might be modified by subsequent calls and therefore makes this function non-reentrant. Otherwise, the Bresult@ argument should be a pointer to an array of at least HL_tmpnam@ characters, and the result is written into that array.
It is possible for Htmpnam@ to fail if you call it too many times without removing previously created files. This is because the fixed length of a temporary file name gives room for only a finite number of different names. If Htmpnam@ fails, it returns a null pointer.À

AFunction:@ char * Dtmpnam_r@ B(char *Bresult@)
Â‰IDX889Š@�”˜This function is nearly identical to the Htmpnam@ function. But it does not allow Bresult@ to be a null pointer. In the later case a null pointer is returned.
This function is reentrant because the non-reentrant situation of Htmpnam@ cannot happen here.À

AMacro:@ int DL_tmpnam
Â‰IDX890Š@�”˜The value of this macro is an integer constant expression that represents the minimum allocation size of a string large enough to hold the file name generated by the Htmpnam@ function.À

AMacro:@ int DTMP_MAX
Â‰IDX891Š@�”˜The macro HTMP_MAX@ is a lower bound for how many temporary names you can create with Htmpnam@. You can rely on being able to call Htmpnam@ at least this many times before it might fail saying you have made too many temporary file names.
With the GNU library, you can create a very large number of temporary file names--if you actually create the files, you will probably run out of disk space before you run out of names. Some other systems have a fixed, small limit on the number of temporary files. The limit is never less than H25@.À

AFunction:@ char * Dtempnam@ B(const char *Bdir@, const char *Bprefix@)
Â‰IDX892Š@�”˜This function generates a unique temporary filename. If Bprefix@ is not a null pointer, up to five characters of this string are used as a prefix for the file name. The return value is a string newly allocated with Hmalloc@; you should release its storage with Hfree@ when it is no longer needed.
Because the string is dynamically allocated this function is reentrant.
The directory prefix for the temporary file name is determined by testing each of the following, in sequence. The directory must exist and be writable. þÄ
• The environment variable HTMPDIR@, if it is defined. For security reasons this only happens if the program is not SUID or SGID enabled.
• The Bdir@ argument, if it is not a null pointer.
• The value of the HP_tmpdir@ macro.
• The directory H`/tmp'@.Âð
This function is defined for SVID compatibility.À
‰IDX893Š

A�”˜SVID Macro:@ char * DP_tmpdir
Â‰IDX894Š@�”˜This macro is the name of the default directory for temporary files.À

Older Unix systems did not have the functions just described. Instead they used Hmktemp@ and Hmkstemp@. Both of these functions work by modifying a file name template string you pass. The last six characters of this string must be H`XXXXXX'@. These six H`X'@s are replaced with six characters which make the whole string a unique file name. Usually the template string is something like H`/tmp/JprefixHXXXXXX'@, and each program uses a unique Bprefix@.
DNote:@ Because Hmktemp@ and Hmkstemp@ modify the template string, you Bmust not@ pass string constants to them. String constants are normally in read-only storage, so your program would crash when Hmktemp@ or Hmkstemp@ tried to modify the string.

AFunction:@ char * Dmktemp@ B(char *Btemplate@)
Â‰IDX895Š@�”˜The Hmktemp@ function generates a unique file name by modifying Btemplate@ as described above. If successful, it returns Btemplate@ as modified. If Hmktemp@ cannot find a unique file name, it makes Btemplate@ an empty string and returns that. If Btemplate@ does not end with H`XXXXXX'@, Hmktemp@ returns a null pointer.À

AFunction:@ int Dmkstemp@ B(char *Btemplate@)
Â‰IDX896Š@�”˜The Hmkstemp@ function generates a unique file name just as Hmktemp@ does, but it also opens the file for you with Hopen@ (see section ‰ŠP�”›Opening and Closing Files@�”˜). If successful, it modifies Btemplate@ in place and returns a file descriptor open on that file for reading and writing. If Hmkstemp@ cannot create a uniquely-named file, it makes Btemplate@ an empty string and returns H-1@. If Btemplate@ does not end with H`XXXXXX'@, Hmkstemp@ returns H-1@ and does not modify Btemplate@.À

Unlike Hmktemp@, Hmkstemp@ is actually guaranteed to create a unique file that cannot possibly clash with any other program trying to create a temporary file. This is because it works by calling Hopen@ with the HO_EXCL@ flag bit, which says you want to always create a new file, and get an error if the file already exists.
Œ
Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.