filesys.texi 159 KB

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