filesys.texi 139 KB

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