📄 filesys.texi
字号:
@node File System Interface, Pipes and FIFOs, Low-Level I/O, Top@chapter File System InterfaceThis chapter describes the GNU C library's functions for manipulatingfiles. Unlike the input and output functions described in@ref{I/O on Streams} and @ref{Low-Level I/O}, thesefunctions are concerned with operating on the files themselves, ratherthan on their contents.Among the facilities described in this chapter are functions forexamining or modifying directories, functions for renaming and deletingfiles, and functions for examining and setting file attributes such asaccess permissions and modification times.@menu* Working Directory:: This is used to resolve relative file names.* Accessing Directories:: Finding out what files a directory contains.* Hard Links:: Adding alternate names to a file.* Symbolic Links:: A file that ``points to'' a file name.* Deleting Files:: How to delete a file, and what that means.* Renaming Files:: Changing a file's name.* Creating Directories:: A system call just for creating a directory.* File Attributes:: Attributes of individual files.* Making Special Files:: How to create special files.* Temporary Files:: Naming and creating temporary files.@end menu@node Working Directory@section Working Directory@cindex current working directory@cindex working directory@cindex change working directoryEach process has associated with it a directory, called its @dfn{currentworking directory} or simply @dfn{working directory}, that is used inthe resolution of relative file names (@pxref{File Name Resolution}).When you log in and begin a new session, your working directory isinitially set to the home directory associated with your login accountin the system user database. You can find any user's home directoryusing the @code{getpwuid} or @code{getpwnam} functions; see @ref{UserDatabase}.Users can change the working directory using shell commands like@code{cd}. The functions described in this section are the primitivesused by those commands and by other programs for examining and changingthe working directory.@pindex cdPrototypes for these functions are declared in the header file@file{unistd.h}.@pindex unistd.h@comment unistd.h@comment POSIX.1@deftypefun {char *} getcwd (char *@var{buffer}, size_t @var{size})The @code{getcwd} function returns an absolute file name representingthe current working directory, storing it in the character array@var{buffer} that you provide. The @var{size} argument is how you tellthe system the allocation size of @var{buffer}.The GNU library version of this function also permits you to specify anull pointer for the @var{buffer} argument. Then @code{getcwd}allocates a buffer automatically, as with @code{malloc}(@pxref{Unconstrained Allocation}). If the @var{size} is greater thanzero, then the buffer is that large; otherwise, the buffer is as largeas necessary to hold the result.The return value is @var{buffer} on success and a null pointer on failure.The following @code{errno} error conditions are defined for this function:@table @code@item EINVALThe @var{size} argument is zero and @var{buffer} is not a null pointer.@item ERANGEThe @var{size} argument is less than the length of the working directoryname. You need to allocate a bigger array and try again.@item EACCESPermission to read or search a component of the file name was denied.@end table@end deftypefunHere is an example showing how you could implement the behavior of GNU's@w{@code{getcwd (NULL, 0)}} using only the standard behavior of@code{getcwd}:@smallexamplechar *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); @}@}@end smallexample@noindent@xref{Malloc Examples}, for information about @code{xmalloc}, which isnot a library function but is a customary name used in most GNUsoftware.@comment unistd.h@comment BSD@deftypefun {char *} getwd (char *@var{buffer})This is similar to @code{getcwd}, but has no way to specify the size ofthe buffer. The GNU library provides @code{getwd} onlyfor backwards compatibility with BSD.The @var{buffer} argument should be a pointer to an array at least@code{PATH_MAX} bytes long (@pxref{Limits for Files}). In the GNUsystem there is no limit to the size of a file name, so this is notnecessarily enough space to contain the directory name. That is whythis function is deprecated.@end deftypefun@comment unistd.h@comment POSIX.1@deftypefun int chdir (const char *@var{filename})This function is used to set the process's working directory to@var{filename}.The normal, successful return value from @code{chdir} is @code{0}. Avalue of @code{-1} is returned to indicate an error. The @code{errno}error conditions defined for this function are the usual file namesyntax errors (@pxref{File Name Errors}), plus @code{ENOTDIR} if thefile @var{filename} is not a directory.@end deftypefun@node Accessing Directories@section Accessing Directories@cindex accessing directories@cindex reading from a directory@cindex directories, accessingThe facilities described in this section let you read the contents of adirectory file. This is useful if you want your program to list all thefiles in a directory, perhaps as part of a menu.@cindex directory streamThe @code{opendir} function opens a @dfn{directory stream} whoseelements are directory entries. You use the @code{readdir} function onthe directory stream to retrieve these entries, represented as@w{@code{struct dirent}} objects. The name of the file for each entry isstored in the @code{d_name} member of this structure. There are obviousparallels here to the stream facilities for ordinary files, described in@ref{I/O on Streams}.@menu* Directory Entries:: Format of one directory entry.* Opening a Directory:: How to open a directory stream.* Reading/Closing Directory:: How to read directory entries from the stream.* Simple Directory Lister:: A very simple directory listing program.* Random Access Directory:: Rereading part of the directory already read with the same stream.@end menu@node Directory Entries@subsection Format of a Directory Entry@pindex dirent.hThis section describes what you find in a single directory entry, as youmight obtain it from a directory stream. All the symbols are declaredin the header file @file{dirent.h}.@comment dirent.h@comment POSIX.1@deftp {Data Type} {struct dirent}This is a structure type used to return information about directoryentries. It contains the following fields:@table @code@item char d_name[]This is the null-terminated file name component. This is the onlyfield you can count on in all POSIX systems.@item ino_t d_filenoThis is the file serial number. For BSD compatibility, you can alsorefer to this member as @code{d_ino}. In the GNU system and most POSIXsystems, for most files this the same as the @code{st_ino} member that@code{stat} will return for the file. @xref{File Attributes}.@item unsigned char d_namlenThis is the length of the file name, not including the terminating nullcharacter. Its type is @code{unsigned char} because that is the integertype of the appropriate size@item unsigned char d_typeThis is the type of the file, possibly unknown. The following constantsare defined for its value:@table @code@item DT_UNKNOWNThe type is unknown. On some systems this is the only value returned.@item DT_REGA regular file.@item DT_DIRA directory.@item DT_FIFOA named pipe, or FIFO. @xref{FIFO Special Files}.@item DT_SOCKA local-domain socket. @c !!! @xref{Local Domain}.@item DT_CHRA character device.@item DT_BLKA block device.@end tableThis member is a BSD extension. Each value except DT_UNKNOWNcorresponds to the file type bits in the @code{st_mode} member of@code{struct statbuf}. These two macros convert between @code{d_type}values and @code{st_mode} values:@deftypefun int IFTODT (mode_t @var{mode})This returns the @code{d_type} value corresponding to @var{mode}.@end deftypefun@deftypefun mode_t DTTOIF (int @var{dirtype})This returns the @code{st_mode} value corresponding to @var{dirtype}.@end deftypefun@end tableThis 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 asingle file is that they have the same value for the @code{d_fileno}field.File attributes such as size, modification times, and the like are partof the file itself, not any particular directory entry. @xref{FileAttributes}.@end deftp@node Opening a Directory@subsection Opening a Directory Stream@pindex dirent.hThis section describes how to open a directory stream. All the symbolsare declared in the header file @file{dirent.h}.@comment dirent.h@comment POSIX.1@deftp {Data Type} DIRThe @code{DIR} data type represents a directory stream. @end deftpYou shouldn't ever allocate objects of the @code{struct dirent} or@code{DIR} data types, since the directory access functions do that foryou. Instead, you refer to these objects using the pointers returned bythe following functions.@comment dirent.h@comment POSIX.1@deftypefun {DIR *} opendir (const char *@var{dirname})The @code{opendir} function opens and returns a directory stream forreading the directory whose file name is @var{dirname}. The stream hastype @code{DIR *}.If unsuccessful, @code{opendir} returns a null pointer. In addition tothe usual file name syntax errors (@pxref{File Name Errors}), thefollowing @code{errno} error conditions are defined for this function:@table @code@item EACCESRead permission is denied for the directory named by @code{dirname}.@item EMFILEThe process has too many files open.@item ENFILEThe entire system, or perhaps the file system which contains thedirectory, cannot support any additional open files at the moment.(This problem cannot happen on the GNU system.)@end tableThe @code{DIR} type is typically implemented using a file descriptor,and the @code{opendir} function in terms of the @code{open} function.@xref{Low-Level I/O}. Directory streams and the underlyingfile descriptors are closed on @code{exec} (@pxref{Executing a File}).@end deftypefun@node Reading/Closing Directory@subsection Reading and Closing a Directory Stream@pindex dirent.hThis section describes how to read directory entries from a directorystream, and how to close the stream when you are done with it. All thesymbols are declared in the header file @file{dirent.h}.@comment dirent.h@comment POSIX.1@deftypefun {struct dirent *} readdir (DIR *@var{dirstream})This function reads the next entry from the directory. It normallyreturns a pointer to a structure containing information about the file.This structure is statically allocated and can be rewritten by asubsequent call.@strong{Portability Note:} On some systems, @code{readdir} may notreturn entries for @file{.} and @file{..}, even though these are alwaysvalid file names in any directory. @xref{File Name Resolution}.If there are no more entries in the directory or an error is detected,@code{readdir} returns a null pointer. The following @code{errno} errorconditions are defined for this function:@table @code@item EBADFThe @var{dirstream} argument is not valid.@end table@end deftypefun@comment dirent.h@comment POSIX.1@deftypefun int closedir (DIR *@var{dirstream})This function closes the directory stream @var{dirstream}. It returns@code{0} on success and @code{-1} on failure. The following @code{errno} error conditions are defined for thisfunction:@table @code@item EBADFThe @var{dirstream} argument is not valid.@end table@end deftypefun@node Simple Directory Lister@subsection Simple Program to List a DirectoryHere's a simple program that prints the names of the files inthe current working directory:@smallexample@include dir.c.texi@end smallexampleThe order in which files appear in a directory tends to be fairlyrandom. A more useful program would sort the entries (perhaps byalphabetizing them) before printing them; see @ref{Array Sort Function}.@c ??? not documented: scandir, alphasort@node Random Access Directory@subsection Random Access in a Directory Stream@pindex dirent.hThis section describes how to reread parts of a directory that you havealready read from an open directory stream. All the symbols aredeclared in the header file @file{dirent.h}.@comment dirent.h
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -