string.texi 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901
  1. @node String and Array Utilities, Character Set Handling, Character Handling, Top
  2. @c %MENU% Utilities for copying and comparing strings and arrays
  3. @chapter String and Array Utilities
  4. Operations on strings (null-terminated byte sequences) are an important part of
  5. many programs. @Theglibc{} provides an extensive set of string
  6. utility functions, including functions for copying, concatenating,
  7. comparing, and searching strings. Many of these functions can also
  8. operate on arbitrary regions of storage; for example, the @code{memcpy}
  9. function can be used to copy the contents of any kind of array.
  10. It's fairly common for beginning C programmers to ``reinvent the wheel''
  11. by duplicating this functionality in their own code, but it pays to
  12. become familiar with the library functions and to make use of them,
  13. since this offers benefits in maintenance, efficiency, and portability.
  14. For instance, you could easily compare one string to another in two
  15. lines of C code, but if you use the built-in @code{strcmp} function,
  16. you're less likely to make a mistake. And, since these library
  17. functions are typically highly optimized, your program may run faster
  18. too.
  19. @menu
  20. * Representation of Strings:: Introduction to basic concepts.
  21. * String/Array Conventions:: Whether to use a string function or an
  22. arbitrary array function.
  23. * String Length:: Determining the length of a string.
  24. * Copying Strings and Arrays:: Functions to copy strings and arrays.
  25. * Concatenating Strings:: Functions to concatenate strings while copying.
  26. * Truncating Strings:: Functions to truncate strings while copying.
  27. * String/Array Comparison:: Functions for byte-wise and character-wise
  28. comparison.
  29. * Collation Functions:: Functions for collating strings.
  30. * Search Functions:: Searching for a specific element or substring.
  31. * Finding Tokens in a String:: Splitting a string into tokens by looking
  32. for delimiters.
  33. * Erasing Sensitive Data:: Clearing memory which contains sensitive
  34. data, after it's no longer needed.
  35. * Shuffling Bytes:: Or how to flash-cook a string.
  36. * Obfuscating Data:: Reversibly obscuring data from casual view.
  37. * Encode Binary Data:: Encoding and Decoding of Binary Data.
  38. * Argz and Envz Vectors:: Null-separated string vectors.
  39. @end menu
  40. @node Representation of Strings
  41. @section Representation of Strings
  42. @cindex string, representation of
  43. This section is a quick summary of string concepts for beginning C
  44. programmers. It describes how strings are represented in C
  45. and some common pitfalls. If you are already familiar with this
  46. material, you can skip this section.
  47. @cindex string
  48. A @dfn{string} is a null-terminated array of bytes of type @code{char},
  49. including the terminating null byte. String-valued
  50. variables are usually declared to be pointers of type @code{char *}.
  51. Such variables do not include space for the text of a string; that has
  52. to be stored somewhere else---in an array variable, a string constant,
  53. or dynamically allocated memory (@pxref{Memory Allocation}). It's up to
  54. you to store the address of the chosen memory space into the pointer
  55. variable. Alternatively you can store a @dfn{null pointer} in the
  56. pointer variable. The null pointer does not point anywhere, so
  57. attempting to reference the string it points to gets an error.
  58. @cindex multibyte character
  59. @cindex multibyte string
  60. @cindex wide string
  61. A @dfn{multibyte character} is a sequence of one or more bytes that
  62. represents a single character using the locale's encoding scheme; a
  63. null byte always represents the null character. A @dfn{multibyte
  64. string} is a string that consists entirely of multibyte
  65. characters. In contrast, a @dfn{wide string} is a null-terminated
  66. sequence of @code{wchar_t} objects. A wide-string variable is usually
  67. declared to be a pointer of type @code{wchar_t *}, by analogy with
  68. string variables and @code{char *}. @xref{Extended Char Intro}.
  69. @cindex null byte
  70. @cindex null wide character
  71. By convention, the @dfn{null byte}, @code{'\0'},
  72. marks the end of a string and the @dfn{null wide character},
  73. @code{L'\0'}, marks the end of a wide string. For example, in
  74. testing to see whether the @code{char *} variable @var{p} points to a
  75. null byte marking the end of a string, you can write
  76. @code{!*@var{p}} or @code{*@var{p} == '\0'}.
  77. A null byte is quite different conceptually from a null pointer,
  78. although both are represented by the integer constant @code{0}.
  79. @cindex string literal
  80. A @dfn{string literal} appears in C program source as a multibyte
  81. string between double-quote characters (@samp{"}). If the
  82. initial double-quote character is immediately preceded by a capital
  83. @samp{L} (ell) character (as in @code{L"foo"}), it is a wide string
  84. literal. String literals can also contribute to @dfn{string
  85. concatenation}: @code{"a" "b"} is the same as @code{"ab"}.
  86. For wide strings one can use either
  87. @code{L"a" L"b"} or @code{L"a" "b"}. Modification of string literals is
  88. not allowed by the GNU C compiler, because literals are placed in
  89. read-only storage.
  90. Arrays that are declared @code{const} cannot be modified
  91. either. It's generally good style to declare non-modifiable string
  92. pointers to be of type @code{const char *}, since this often allows the
  93. C compiler to detect accidental modifications as well as providing some
  94. amount of documentation about what your program intends to do with the
  95. string.
  96. The amount of memory allocated for a byte array may extend past the null byte
  97. that marks the end of the string that the array contains. In this
  98. document, the term @dfn{allocated size} is always used to refer to the
  99. total amount of memory allocated for an array, while the term
  100. @dfn{length} refers to the number of bytes up to (but not including)
  101. the terminating null byte. Wide strings are similar, except their
  102. sizes and lengths count wide characters, not bytes.
  103. @cindex length of string
  104. @cindex allocation size of string
  105. @cindex size of string
  106. @cindex string length
  107. @cindex string allocation
  108. A notorious source of program bugs is trying to put more bytes into a
  109. string than fit in its allocated size. When writing code that extends
  110. strings or moves bytes into a pre-allocated array, you should be
  111. very careful to keep track of the length of the text and make explicit
  112. checks for overflowing the array. Many of the library functions
  113. @emph{do not} do this for you! Remember also that you need to allocate
  114. an extra byte to hold the null byte that marks the end of the
  115. string.
  116. @cindex single-byte string
  117. @cindex multibyte string
  118. Originally strings were sequences of bytes where each byte represented a
  119. single character. This is still true today if the strings are encoded
  120. using a single-byte character encoding. Things are different if the
  121. strings are encoded using a multibyte encoding (for more information on
  122. encodings see @ref{Extended Char Intro}). There is no difference in
  123. the programming interface for these two kind of strings; the programmer
  124. has to be aware of this and interpret the byte sequences accordingly.
  125. But since there is no separate interface taking care of these
  126. differences the byte-based string functions are sometimes hard to use.
  127. Since the count parameters of these functions specify bytes a call to
  128. @code{memcpy} could cut a multibyte character in the middle and put an
  129. incomplete (and therefore unusable) byte sequence in the target buffer.
  130. @cindex wide string
  131. To avoid these problems later versions of the @w{ISO C} standard
  132. introduce a second set of functions which are operating on @dfn{wide
  133. characters} (@pxref{Extended Char Intro}). These functions don't have
  134. the problems the single-byte versions have since every wide character is
  135. a legal, interpretable value. This does not mean that cutting wide
  136. strings at arbitrary points is without problems. It normally
  137. is for alphabet-based languages (except for non-normalized text) but
  138. languages based on syllables still have the problem that more than one
  139. wide character is necessary to complete a logical unit. This is a
  140. higher level problem which the @w{C library} functions are not designed
  141. to solve. But it is at least good that no invalid byte sequences can be
  142. created. Also, the higher level functions can also much more easily operate
  143. on wide characters than on multibyte characters so that a common strategy
  144. is to use wide characters internally whenever text is more than simply
  145. copied.
  146. The remaining of this chapter will discuss the functions for handling
  147. wide strings in parallel with the discussion of
  148. strings since there is almost always an exact equivalent
  149. available.
  150. @node String/Array Conventions
  151. @section String and Array Conventions
  152. This chapter describes both functions that work on arbitrary arrays or
  153. blocks of memory, and functions that are specific to strings and wide
  154. strings.
  155. Functions that operate on arbitrary blocks of memory have names
  156. beginning with @samp{mem} and @samp{wmem} (such as @code{memcpy} and
  157. @code{wmemcpy}) and invariably take an argument which specifies the size
  158. (in bytes and wide characters respectively) of the block of memory to
  159. operate on. The array arguments and return values for these functions
  160. have type @code{void *} or @code{wchar_t}. As a matter of style, the
  161. elements of the arrays used with the @samp{mem} functions are referred
  162. to as ``bytes''. You can pass any kind of pointer to these functions,
  163. and the @code{sizeof} operator is useful in computing the value for the
  164. size argument. Parameters to the @samp{wmem} functions must be of type
  165. @code{wchar_t *}. These functions are not really usable with anything
  166. but arrays of this type.
  167. In contrast, functions that operate specifically on strings and wide
  168. strings have names beginning with @samp{str} and @samp{wcs}
  169. respectively (such as @code{strcpy} and @code{wcscpy}) and look for a
  170. terminating null byte or null wide character instead of requiring an explicit
  171. size argument to be passed. (Some of these functions accept a specified
  172. maximum length, but they also check for premature termination.)
  173. The array arguments and return values for these
  174. functions have type @code{char *} and @code{wchar_t *} respectively, and
  175. the array elements are referred to as ``bytes'' and ``wide
  176. characters''.
  177. In many cases, there are both @samp{mem} and @samp{str}/@samp{wcs}
  178. versions of a function. The one that is more appropriate to use depends
  179. on the exact situation. When your program is manipulating arbitrary
  180. arrays or blocks of storage, then you should always use the @samp{mem}
  181. functions. On the other hand, when you are manipulating
  182. strings it is usually more convenient to use the @samp{str}/@samp{wcs}
  183. functions, unless you already know the length of the string in advance.
  184. The @samp{wmem} functions should be used for wide character arrays with
  185. known size.
  186. @cindex wint_t
  187. @cindex parameter promotion
  188. Some of the memory and string functions take single characters as
  189. arguments. Since a value of type @code{char} is automatically promoted
  190. into a value of type @code{int} when used as a parameter, the functions
  191. are declared with @code{int} as the type of the parameter in question.
  192. In case of the wide character functions the situation is similar: the
  193. parameter type for a single wide character is @code{wint_t} and not
  194. @code{wchar_t}. This would for many implementations not be necessary
  195. since @code{wchar_t} is large enough to not be automatically
  196. promoted, but since the @w{ISO C} standard does not require such a
  197. choice of types the @code{wint_t} type is used.
  198. @node String Length
  199. @section String Length
  200. You can get the length of a string using the @code{strlen} function.
  201. This function is declared in the header file @file{string.h}.
  202. @pindex string.h
  203. @deftypefun size_t strlen (const char *@var{s})
  204. @standards{ISO, string.h}
  205. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  206. The @code{strlen} function returns the length of the
  207. string @var{s} in bytes. (In other words, it returns the offset of the
  208. terminating null byte within the array.)
  209. For example,
  210. @smallexample
  211. strlen ("hello, world")
  212. @result{} 12
  213. @end smallexample
  214. When applied to an array, the @code{strlen} function returns
  215. the length of the string stored there, not its allocated size. You can
  216. get the allocated size of the array that holds a string using
  217. the @code{sizeof} operator:
  218. @smallexample
  219. char string[32] = "hello, world";
  220. sizeof (string)
  221. @result{} 32
  222. strlen (string)
  223. @result{} 12
  224. @end smallexample
  225. But beware, this will not work unless @var{string} is the
  226. array itself, not a pointer to it. For example:
  227. @smallexample
  228. char string[32] = "hello, world";
  229. char *ptr = string;
  230. sizeof (string)
  231. @result{} 32
  232. sizeof (ptr)
  233. @result{} 4 /* @r{(on a machine with 4 byte pointers)} */
  234. @end smallexample
  235. This is an easy mistake to make when you are working with functions that
  236. take string arguments; those arguments are always pointers, not arrays.
  237. It must also be noted that for multibyte encoded strings the return
  238. value does not have to correspond to the number of characters in the
  239. string. To get this value the string can be converted to wide
  240. characters and @code{wcslen} can be used or something like the following
  241. code can be used:
  242. @smallexample
  243. /* @r{The input is in @code{string}.}
  244. @r{The length is expected in @code{n}.} */
  245. @{
  246. mbstate_t t;
  247. char *scopy = string;
  248. /* In initial state. */
  249. memset (&t, '\0', sizeof (t));
  250. /* Determine number of characters. */
  251. n = mbsrtowcs (NULL, &scopy, strlen (scopy), &t);
  252. @}
  253. @end smallexample
  254. This is cumbersome to do so if the number of characters (as opposed to
  255. bytes) is needed often it is better to work with wide characters.
  256. @end deftypefun
  257. The wide character equivalent is declared in @file{wchar.h}.
  258. @deftypefun size_t wcslen (const wchar_t *@var{ws})
  259. @standards{ISO, wchar.h}
  260. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  261. The @code{wcslen} function is the wide character equivalent to
  262. @code{strlen}. The return value is the number of wide characters in the
  263. wide string pointed to by @var{ws} (this is also the offset of
  264. the terminating null wide character of @var{ws}).
  265. Since there are no multi wide character sequences making up one wide
  266. character the return value is not only the offset in the array, it is
  267. also the number of wide characters.
  268. This function was introduced in @w{Amendment 1} to @w{ISO C90}.
  269. @end deftypefun
  270. @deftypefun size_t strnlen (const char *@var{s}, size_t @var{maxlen})
  271. @standards{GNU, string.h}
  272. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  273. If the array @var{s} of size @var{maxlen} contains a null byte,
  274. the @code{strnlen} function returns the length of the string @var{s} in
  275. bytes. Otherwise it
  276. returns @var{maxlen}. Therefore this function is equivalent to
  277. @code{(strlen (@var{s}) < @var{maxlen} ? strlen (@var{s}) : @var{maxlen})}
  278. but it
  279. is more efficient and works even if @var{s} is not null-terminated so
  280. long as @var{maxlen} does not exceed the size of @var{s}'s array.
  281. @smallexample
  282. char string[32] = "hello, world";
  283. strnlen (string, 32)
  284. @result{} 12
  285. strnlen (string, 5)
  286. @result{} 5
  287. @end smallexample
  288. This function is a GNU extension and is declared in @file{string.h}.
  289. @end deftypefun
  290. @deftypefun size_t wcsnlen (const wchar_t *@var{ws}, size_t @var{maxlen})
  291. @standards{GNU, wchar.h}
  292. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  293. @code{wcsnlen} is the wide character equivalent to @code{strnlen}. The
  294. @var{maxlen} parameter specifies the maximum number of wide characters.
  295. This function is a GNU extension and is declared in @file{wchar.h}.
  296. @end deftypefun
  297. @node Copying Strings and Arrays
  298. @section Copying Strings and Arrays
  299. You can use the functions described in this section to copy the contents
  300. of strings, wide strings, and arrays. The @samp{str} and @samp{mem}
  301. functions are declared in @file{string.h} while the @samp{w} functions
  302. are declared in @file{wchar.h}.
  303. @pindex string.h
  304. @pindex wchar.h
  305. @cindex copying strings and arrays
  306. @cindex string copy functions
  307. @cindex array copy functions
  308. @cindex concatenating strings
  309. @cindex string concatenation functions
  310. A helpful way to remember the ordering of the arguments to the functions
  311. in this section is that it corresponds to an assignment expression, with
  312. the destination array specified to the left of the source array. Most
  313. of these functions return the address of the destination array; a few
  314. return the address of the destination's terminating null, or of just
  315. past the destination.
  316. Most of these functions do not work properly if the source and
  317. destination arrays overlap. For example, if the beginning of the
  318. destination array overlaps the end of the source array, the original
  319. contents of that part of the source array may get overwritten before it
  320. is copied. Even worse, in the case of the string functions, the null
  321. byte marking the end of the string may be lost, and the copy
  322. function might get stuck in a loop trashing all the memory allocated to
  323. your program.
  324. All functions that have problems copying between overlapping arrays are
  325. explicitly identified in this manual. In addition to functions in this
  326. section, there are a few others like @code{sprintf} (@pxref{Formatted
  327. Output Functions}) and @code{scanf} (@pxref{Formatted Input
  328. Functions}).
  329. @deftypefun {void *} memcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
  330. @standards{ISO, string.h}
  331. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  332. The @code{memcpy} function copies @var{size} bytes from the object
  333. beginning at @var{from} into the object beginning at @var{to}. The
  334. behavior of this function is undefined if the two arrays @var{to} and
  335. @var{from} overlap; use @code{memmove} instead if overlapping is possible.
  336. The value returned by @code{memcpy} is the value of @var{to}.
  337. Here is an example of how you might use @code{memcpy} to copy the
  338. contents of an array:
  339. @smallexample
  340. struct foo *oldarray, *newarray;
  341. int arraysize;
  342. @dots{}
  343. memcpy (new, old, arraysize * sizeof (struct foo));
  344. @end smallexample
  345. @end deftypefun
  346. @deftypefun {wchar_t *} wmemcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
  347. @standards{ISO, wchar.h}
  348. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  349. The @code{wmemcpy} function copies @var{size} wide characters from the object
  350. beginning at @var{wfrom} into the object beginning at @var{wto}. The
  351. behavior of this function is undefined if the two arrays @var{wto} and
  352. @var{wfrom} overlap; use @code{wmemmove} instead if overlapping is possible.
  353. The following is a possible implementation of @code{wmemcpy} but there
  354. are more optimizations possible.
  355. @smallexample
  356. wchar_t *
  357. wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
  358. size_t size)
  359. @{
  360. return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));
  361. @}
  362. @end smallexample
  363. The value returned by @code{wmemcpy} is the value of @var{wto}.
  364. This function was introduced in @w{Amendment 1} to @w{ISO C90}.
  365. @end deftypefun
  366. @deftypefun {void *} mempcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
  367. @standards{GNU, string.h}
  368. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  369. The @code{mempcpy} function is nearly identical to the @code{memcpy}
  370. function. It copies @var{size} bytes from the object beginning at
  371. @code{from} into the object pointed to by @var{to}. But instead of
  372. returning the value of @var{to} it returns a pointer to the byte
  373. following the last written byte in the object beginning at @var{to}.
  374. I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
  375. This function is useful in situations where a number of objects shall be
  376. copied to consecutive memory positions.
  377. @smallexample
  378. void *
  379. combine (void *o1, size_t s1, void *o2, size_t s2)
  380. @{
  381. void *result = malloc (s1 + s2);
  382. if (result != NULL)
  383. mempcpy (mempcpy (result, o1, s1), o2, s2);
  384. return result;
  385. @}
  386. @end smallexample
  387. This function is a GNU extension.
  388. @end deftypefun
  389. @deftypefun {wchar_t *} wmempcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
  390. @standards{GNU, wchar.h}
  391. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  392. The @code{wmempcpy} function is nearly identical to the @code{wmemcpy}
  393. function. It copies @var{size} wide characters from the object
  394. beginning at @code{wfrom} into the object pointed to by @var{wto}. But
  395. instead of returning the value of @var{wto} it returns a pointer to the
  396. wide character following the last written wide character in the object
  397. beginning at @var{wto}. I.e., the value is @code{@var{wto} + @var{size}}.
  398. This function is useful in situations where a number of objects shall be
  399. copied to consecutive memory positions.
  400. The following is a possible implementation of @code{wmemcpy} but there
  401. are more optimizations possible.
  402. @smallexample
  403. wchar_t *
  404. wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
  405. size_t size)
  406. @{
  407. return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
  408. @}
  409. @end smallexample
  410. This function is a GNU extension.
  411. @end deftypefun
  412. @deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
  413. @standards{ISO, string.h}
  414. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  415. @code{memmove} copies the @var{size} bytes at @var{from} into the
  416. @var{size} bytes at @var{to}, even if those two blocks of space
  417. overlap. In the case of overlap, @code{memmove} is careful to copy the
  418. original values of the bytes in the block at @var{from}, including those
  419. bytes which also belong to the block at @var{to}.
  420. The value returned by @code{memmove} is the value of @var{to}.
  421. @end deftypefun
  422. @deftypefun {wchar_t *} wmemmove (wchar_t *@var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
  423. @standards{ISO, wchar.h}
  424. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  425. @code{wmemmove} copies the @var{size} wide characters at @var{wfrom}
  426. into the @var{size} wide characters at @var{wto}, even if those two
  427. blocks of space overlap. In the case of overlap, @code{wmemmove} is
  428. careful to copy the original values of the wide characters in the block
  429. at @var{wfrom}, including those wide characters which also belong to the
  430. block at @var{wto}.
  431. The following is a possible implementation of @code{wmemcpy} but there
  432. are more optimizations possible.
  433. @smallexample
  434. wchar_t *
  435. wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
  436. size_t size)
  437. @{
  438. return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
  439. @}
  440. @end smallexample
  441. The value returned by @code{wmemmove} is the value of @var{wto}.
  442. This function is a GNU extension.
  443. @end deftypefun
  444. @deftypefun {void *} memccpy (void *restrict @var{to}, const void *restrict @var{from}, int @var{c}, size_t @var{size})
  445. @standards{SVID, string.h}
  446. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  447. This function copies no more than @var{size} bytes from @var{from} to
  448. @var{to}, stopping if a byte matching @var{c} is found. The return
  449. value is a pointer into @var{to} one byte past where @var{c} was copied,
  450. or a null pointer if no byte matching @var{c} appeared in the first
  451. @var{size} bytes of @var{from}.
  452. @end deftypefun
  453. @deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
  454. @standards{ISO, string.h}
  455. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  456. This function copies the value of @var{c} (converted to an
  457. @code{unsigned char}) into each of the first @var{size} bytes of the
  458. object beginning at @var{block}. It returns the value of @var{block}.
  459. @end deftypefun
  460. @deftypefun {wchar_t *} wmemset (wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
  461. @standards{ISO, wchar.h}
  462. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  463. This function copies the value of @var{wc} into each of the first
  464. @var{size} wide characters of the object beginning at @var{block}. It
  465. returns the value of @var{block}.
  466. @end deftypefun
  467. @deftypefun {char *} strcpy (char *restrict @var{to}, const char *restrict @var{from})
  468. @standards{ISO, string.h}
  469. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  470. This copies bytes from the string @var{from} (up to and including
  471. the terminating null byte) into the string @var{to}. Like
  472. @code{memcpy}, this function has undefined results if the strings
  473. overlap. The return value is the value of @var{to}.
  474. @end deftypefun
  475. @deftypefun {wchar_t *} wcscpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
  476. @standards{ISO, wchar.h}
  477. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  478. This copies wide characters from the wide string @var{wfrom} (up to and
  479. including the terminating null wide character) into the string
  480. @var{wto}. Like @code{wmemcpy}, this function has undefined results if
  481. the strings overlap. The return value is the value of @var{wto}.
  482. @end deftypefun
  483. @deftypefun {char *} strdup (const char *@var{s})
  484. @standards{SVID, string.h}
  485. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  486. This function copies the string @var{s} into a newly
  487. allocated string. The string is allocated using @code{malloc}; see
  488. @ref{Unconstrained Allocation}. If @code{malloc} cannot allocate space
  489. for the new string, @code{strdup} returns a null pointer. Otherwise it
  490. returns a pointer to the new string.
  491. @end deftypefun
  492. @deftypefun {wchar_t *} wcsdup (const wchar_t *@var{ws})
  493. @standards{GNU, wchar.h}
  494. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  495. This function copies the wide string @var{ws}
  496. into a newly allocated string. The string is allocated using
  497. @code{malloc}; see @ref{Unconstrained Allocation}. If @code{malloc}
  498. cannot allocate space for the new string, @code{wcsdup} returns a null
  499. pointer. Otherwise it returns a pointer to the new wide string.
  500. This function is a GNU extension.
  501. @end deftypefun
  502. @deftypefun {char *} stpcpy (char *restrict @var{to}, const char *restrict @var{from})
  503. @standards{Unknown origin, string.h}
  504. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  505. This function is like @code{strcpy}, except that it returns a pointer to
  506. the end of the string @var{to} (that is, the address of the terminating
  507. null byte @code{to + strlen (from)}) rather than the beginning.
  508. For example, this program uses @code{stpcpy} to concatenate @samp{foo}
  509. and @samp{bar} to produce @samp{foobar}, which it then prints.
  510. @smallexample
  511. @include stpcpy.c.texi
  512. @end smallexample
  513. This function is part of POSIX.1-2008 and later editions, but was
  514. available in @theglibc{} and other systems as an extension long before
  515. it was standardized.
  516. Its behavior is undefined if the strings overlap. The function is
  517. declared in @file{string.h}.
  518. @end deftypefun
  519. @deftypefun {wchar_t *} wcpcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
  520. @standards{GNU, wchar.h}
  521. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  522. This function is like @code{wcscpy}, except that it returns a pointer to
  523. the end of the string @var{wto} (that is, the address of the terminating
  524. null wide character @code{wto + wcslen (wfrom)}) rather than the beginning.
  525. This function is not part of ISO or POSIX but was found useful while
  526. developing @theglibc{} itself.
  527. The behavior of @code{wcpcpy} is undefined if the strings overlap.
  528. @code{wcpcpy} is a GNU extension and is declared in @file{wchar.h}.
  529. @end deftypefun
  530. @deftypefn {Macro} {char *} strdupa (const char *@var{s})
  531. @standards{GNU, string.h}
  532. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  533. This macro is similar to @code{strdup} but allocates the new string
  534. using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
  535. Automatic}). This means of course the returned string has the same
  536. limitations as any block of memory allocated using @code{alloca}.
  537. For obvious reasons @code{strdupa} is implemented only as a macro;
  538. you cannot get the address of this function. Despite this limitation
  539. it is a useful function. The following code shows a situation where
  540. using @code{malloc} would be a lot more expensive.
  541. @smallexample
  542. @include strdupa.c.texi
  543. @end smallexample
  544. Please note that calling @code{strtok} using @var{path} directly is
  545. invalid. It is also not allowed to call @code{strdupa} in the argument
  546. list of @code{strtok} since @code{strdupa} uses @code{alloca}
  547. (@pxref{Variable Size Automatic}) can interfere with the parameter
  548. passing.
  549. This function is only available if GNU CC is used.
  550. @end deftypefn
  551. @deftypefun void bcopy (const void *@var{from}, void *@var{to}, size_t @var{size})
  552. @standards{BSD, string.h}
  553. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  554. This is a partially obsolete alternative for @code{memmove}, derived from
  555. BSD. Note that it is not quite equivalent to @code{memmove}, because the
  556. arguments are not in the same order and there is no return value.
  557. @end deftypefun
  558. @deftypefun void bzero (void *@var{block}, size_t @var{size})
  559. @standards{BSD, string.h}
  560. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  561. This is a partially obsolete alternative for @code{memset}, derived from
  562. BSD. Note that it is not as general as @code{memset}, because the only
  563. value it can store is zero.
  564. @end deftypefun
  565. @node Concatenating Strings
  566. @section Concatenating Strings
  567. @pindex string.h
  568. @pindex wchar.h
  569. @cindex concatenating strings
  570. @cindex string concatenation functions
  571. The functions described in this section concatenate the contents of a
  572. string or wide string to another. They follow the string-copying
  573. functions in their conventions. @xref{Copying Strings and Arrays}.
  574. @samp{strcat} is declared in the header file @file{string.h} while
  575. @samp{wcscat} is declared in @file{wchar.h}.
  576. @deftypefun {char *} strcat (char *restrict @var{to}, const char *restrict @var{from})
  577. @standards{ISO, string.h}
  578. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  579. The @code{strcat} function is similar to @code{strcpy}, except that the
  580. bytes from @var{from} are concatenated or appended to the end of
  581. @var{to}, instead of overwriting it. That is, the first byte from
  582. @var{from} overwrites the null byte marking the end of @var{to}.
  583. An equivalent definition for @code{strcat} would be:
  584. @smallexample
  585. char *
  586. strcat (char *restrict to, const char *restrict from)
  587. @{
  588. strcpy (to + strlen (to), from);
  589. return to;
  590. @}
  591. @end smallexample
  592. This function has undefined results if the strings overlap.
  593. As noted below, this function has significant performance issues.
  594. @end deftypefun
  595. @deftypefun {wchar_t *} wcscat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
  596. @standards{ISO, wchar.h}
  597. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  598. The @code{wcscat} function is similar to @code{wcscpy}, except that the
  599. wide characters from @var{wfrom} are concatenated or appended to the end of
  600. @var{wto}, instead of overwriting it. That is, the first wide character from
  601. @var{wfrom} overwrites the null wide character marking the end of @var{wto}.
  602. An equivalent definition for @code{wcscat} would be:
  603. @smallexample
  604. wchar_t *
  605. wcscat (wchar_t *wto, const wchar_t *wfrom)
  606. @{
  607. wcscpy (wto + wcslen (wto), wfrom);
  608. return wto;
  609. @}
  610. @end smallexample
  611. This function has undefined results if the strings overlap.
  612. As noted below, this function has significant performance issues.
  613. @end deftypefun
  614. Programmers using the @code{strcat} or @code{wcscat} function (or the
  615. @code{strncat} or @code{wcsncat} functions defined in
  616. a later section, for that matter)
  617. can easily be recognized as lazy and reckless. In almost all situations
  618. the lengths of the participating strings are known (it better should be
  619. since how can one otherwise ensure the allocated size of the buffer is
  620. sufficient?) Or at least, one could know them if one keeps track of the
  621. results of the various function calls. But then it is very inefficient
  622. to use @code{strcat}/@code{wcscat}. A lot of time is wasted finding the
  623. end of the destination string so that the actual copying can start.
  624. This is a common example:
  625. @cindex va_copy
  626. @smallexample
  627. /* @r{This function concatenates arbitrarily many strings. The last}
  628. @r{parameter must be @code{NULL}.} */
  629. char *
  630. concat (const char *str, @dots{})
  631. @{
  632. va_list ap, ap2;
  633. size_t total = 1;
  634. const char *s;
  635. char *result;
  636. va_start (ap, str);
  637. va_copy (ap2, ap);
  638. /* @r{Determine how much space we need.} */
  639. for (s = str; s != NULL; s = va_arg (ap, const char *))
  640. total += strlen (s);
  641. va_end (ap);
  642. result = (char *) malloc (total);
  643. if (result != NULL)
  644. @{
  645. result[0] = '\0';
  646. /* @r{Copy the strings.} */
  647. for (s = str; s != NULL; s = va_arg (ap2, const char *))
  648. strcat (result, s);
  649. @}
  650. va_end (ap2);
  651. return result;
  652. @}
  653. @end smallexample
  654. This looks quite simple, especially the second loop where the strings
  655. are actually copied. But these innocent lines hide a major performance
  656. penalty. Just imagine that ten strings of 100 bytes each have to be
  657. concatenated. For the second string we search the already stored 100
  658. bytes for the end of the string so that we can append the next string.
  659. For all strings in total the comparisons necessary to find the end of
  660. the intermediate results sums up to 5500! If we combine the copying
  661. with the search for the allocation we can write this function more
  662. efficiently:
  663. @smallexample
  664. char *
  665. concat (const char *str, @dots{})
  666. @{
  667. va_list ap;
  668. size_t allocated = 100;
  669. char *result = (char *) malloc (allocated);
  670. if (result != NULL)
  671. @{
  672. char *newp;
  673. char *wp;
  674. const char *s;
  675. va_start (ap, str);
  676. wp = result;
  677. for (s = str; s != NULL; s = va_arg (ap, const char *))
  678. @{
  679. size_t len = strlen (s);
  680. /* @r{Resize the allocated memory if necessary.} */
  681. if (wp + len + 1 > result + allocated)
  682. @{
  683. allocated = (allocated + len) * 2;
  684. newp = (char *) realloc (result, allocated);
  685. if (newp == NULL)
  686. @{
  687. free (result);
  688. return NULL;
  689. @}
  690. wp = newp + (wp - result);
  691. result = newp;
  692. @}
  693. wp = mempcpy (wp, s, len);
  694. @}
  695. /* @r{Terminate the result string.} */
  696. *wp++ = '\0';
  697. /* @r{Resize memory to the optimal size.} */
  698. newp = realloc (result, wp - result);
  699. if (newp != NULL)
  700. result = newp;
  701. va_end (ap);
  702. @}
  703. return result;
  704. @}
  705. @end smallexample
  706. With a bit more knowledge about the input strings one could fine-tune
  707. the memory allocation. The difference we are pointing to here is that
  708. we don't use @code{strcat} anymore. We always keep track of the length
  709. of the current intermediate result so we can save ourselves the search for the
  710. end of the string and use @code{mempcpy}. Please note that we also
  711. don't use @code{stpcpy} which might seem more natural since we are handling
  712. strings. But this is not necessary since we already know the
  713. length of the string and therefore can use the faster memory copying
  714. function. The example would work for wide characters the same way.
  715. Whenever a programmer feels the need to use @code{strcat} she or he
  716. should think twice and look through the program to see whether the code cannot
  717. be rewritten to take advantage of already calculated results. Again: it
  718. is almost always unnecessary to use @code{strcat}.
  719. @node Truncating Strings
  720. @section Truncating Strings while Copying
  721. @cindex truncating strings
  722. @cindex string truncation
  723. The functions described in this section copy or concatenate the
  724. possibly-truncated contents of a string or array to another, and
  725. similarly for wide strings. They follow the string-copying functions
  726. in their header conventions. @xref{Copying Strings and Arrays}. The
  727. @samp{str} functions are declared in the header file @file{string.h}
  728. and the @samp{wc} functions are declared in the file @file{wchar.h}.
  729. @deftypefun {char *} strncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
  730. @standards{C90, string.h}
  731. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  732. This function is similar to @code{strcpy} but always copies exactly
  733. @var{size} bytes into @var{to}.
  734. If @var{from} does not contain a null byte in its first @var{size}
  735. bytes, @code{strncpy} copies just the first @var{size} bytes. In this
  736. case no null terminator is written into @var{to}.
  737. Otherwise @var{from} must be a string with length less than
  738. @var{size}. In this case @code{strncpy} copies all of @var{from},
  739. followed by enough null bytes to add up to @var{size} bytes in all.
  740. The behavior of @code{strncpy} is undefined if the strings overlap.
  741. This function was designed for now-rarely-used arrays consisting of
  742. non-null bytes followed by zero or more null bytes. It needs to set
  743. all @var{size} bytes of the destination, even when @var{size} is much
  744. greater than the length of @var{from}. As noted below, this function
  745. is generally a poor choice for processing text.
  746. @end deftypefun
  747. @deftypefun {wchar_t *} wcsncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
  748. @standards{ISO, wchar.h}
  749. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  750. This function is similar to @code{wcscpy} but always copies exactly
  751. @var{size} wide characters into @var{wto}.
  752. If @var{wfrom} does not contain a null wide character in its first
  753. @var{size} wide characters, then @code{wcsncpy} copies just the first
  754. @var{size} wide characters. In this case no null terminator is
  755. written into @var{wto}.
  756. Otherwise @var{wfrom} must be a wide string with length less than
  757. @var{size}. In this case @code{wcsncpy} copies all of @var{wfrom},
  758. followed by enough null wide characters to add up to @var{size} wide
  759. characters in all.
  760. The behavior of @code{wcsncpy} is undefined if the strings overlap.
  761. This function is the wide-character counterpart of @code{strncpy} and
  762. suffers from most of the problems that @code{strncpy} does. For
  763. example, as noted below, this function is generally a poor choice for
  764. processing text.
  765. @end deftypefun
  766. @deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
  767. @standards{GNU, string.h}
  768. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  769. This function is similar to @code{strdup} but always copies at most
  770. @var{size} bytes into the newly allocated string.
  771. If the length of @var{s} is more than @var{size}, then @code{strndup}
  772. copies just the first @var{size} bytes and adds a closing null byte.
  773. Otherwise all bytes are copied and the string is terminated.
  774. This function differs from @code{strncpy} in that it always terminates
  775. the destination string.
  776. As noted below, this function is generally a poor choice for
  777. processing text.
  778. @code{strndup} is a GNU extension.
  779. @end deftypefun
  780. @deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
  781. @standards{GNU, string.h}
  782. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  783. This function is similar to @code{strndup} but like @code{strdupa} it
  784. allocates the new string using @code{alloca} @pxref{Variable Size
  785. Automatic}. The same advantages and limitations of @code{strdupa} are
  786. valid for @code{strndupa}, too.
  787. This function is implemented only as a macro, just like @code{strdupa}.
  788. Just as @code{strdupa} this macro also must not be used inside the
  789. parameter list in a function call.
  790. As noted below, this function is generally a poor choice for
  791. processing text.
  792. @code{strndupa} is only available if GNU CC is used.
  793. @end deftypefn
  794. @deftypefun {char *} stpncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
  795. @standards{GNU, string.h}
  796. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  797. This function is similar to @code{stpcpy} but copies always exactly
  798. @var{size} bytes into @var{to}.
  799. If the length of @var{from} is more than @var{size}, then @code{stpncpy}
  800. copies just the first @var{size} bytes and returns a pointer to the
  801. byte directly following the one which was copied last. Note that in
  802. this case there is no null terminator written into @var{to}.
  803. If the length of @var{from} is less than @var{size}, then @code{stpncpy}
  804. copies all of @var{from}, followed by enough null bytes to add up
  805. to @var{size} bytes in all. This behavior is rarely useful, but it
  806. is implemented to be useful in contexts where this behavior of the
  807. @code{strncpy} is used. @code{stpncpy} returns a pointer to the
  808. @emph{first} written null byte.
  809. This function is not part of ISO or POSIX but was found useful while
  810. developing @theglibc{} itself.
  811. Its behavior is undefined if the strings overlap. The function is
  812. declared in @file{string.h}.
  813. As noted below, this function is generally a poor choice for
  814. processing text.
  815. @end deftypefun
  816. @deftypefun {wchar_t *} wcpncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
  817. @standards{GNU, wchar.h}
  818. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  819. This function is similar to @code{wcpcpy} but copies always exactly
  820. @var{wsize} wide characters into @var{wto}.
  821. If the length of @var{wfrom} is more than @var{size}, then
  822. @code{wcpncpy} copies just the first @var{size} wide characters and
  823. returns a pointer to the wide character directly following the last
  824. non-null wide character which was copied last. Note that in this case
  825. there is no null terminator written into @var{wto}.
  826. If the length of @var{wfrom} is less than @var{size}, then @code{wcpncpy}
  827. copies all of @var{wfrom}, followed by enough null wide characters to add up
  828. to @var{size} wide characters in all. This behavior is rarely useful, but it
  829. is implemented to be useful in contexts where this behavior of the
  830. @code{wcsncpy} is used. @code{wcpncpy} returns a pointer to the
  831. @emph{first} written null wide character.
  832. This function is not part of ISO or POSIX but was found useful while
  833. developing @theglibc{} itself.
  834. Its behavior is undefined if the strings overlap.
  835. As noted below, this function is generally a poor choice for
  836. processing text.
  837. @code{wcpncpy} is a GNU extension.
  838. @end deftypefun
  839. @deftypefun {char *} strncat (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
  840. @standards{ISO, string.h}
  841. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  842. This function is like @code{strcat} except that not more than @var{size}
  843. bytes from @var{from} are appended to the end of @var{to}, and
  844. @var{from} need not be null-terminated. A single null byte is also
  845. always appended to @var{to}, so the total
  846. allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
  847. longer than its initial length.
  848. The @code{strncat} function could be implemented like this:
  849. @smallexample
  850. @group
  851. char *
  852. strncat (char *to, const char *from, size_t size)
  853. @{
  854. size_t len = strlen (to);
  855. memcpy (to + len, from, strnlen (from, size));
  856. to[len + strnlen (from, size)] = '\0';
  857. return to;
  858. @}
  859. @end group
  860. @end smallexample
  861. The behavior of @code{strncat} is undefined if the strings overlap.
  862. As a companion to @code{strncpy}, @code{strncat} was designed for
  863. now-rarely-used arrays consisting of non-null bytes followed by zero
  864. or more null bytes. As noted below, this function is generally a poor
  865. choice for processing text. Also, this function has significant
  866. performance issues. @xref{Concatenating Strings}.
  867. @end deftypefun
  868. @deftypefun {wchar_t *} wcsncat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
  869. @standards{ISO, wchar.h}
  870. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  871. This function is like @code{wcscat} except that not more than @var{size}
  872. wide characters from @var{from} are appended to the end of @var{to},
  873. and @var{from} need not be null-terminated. A single null wide
  874. character is also always appended to @var{to}, so the total allocated
  875. size of @var{to} must be at least @code{wcsnlen (@var{wfrom},
  876. @var{size}) + 1} wide characters longer than its initial length.
  877. The @code{wcsncat} function could be implemented like this:
  878. @smallexample
  879. @group
  880. wchar_t *
  881. wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom,
  882. size_t size)
  883. @{
  884. size_t len = wcslen (wto);
  885. memcpy (wto + len, wfrom, wcsnlen (wfrom, size) * sizeof (wchar_t));
  886. wto[len + wcsnlen (wfrom, size)] = L'\0';
  887. return wto;
  888. @}
  889. @end group
  890. @end smallexample
  891. The behavior of @code{wcsncat} is undefined if the strings overlap.
  892. As noted below, this function is generally a poor choice for
  893. processing text. Also, this function has significant performance
  894. issues. @xref{Concatenating Strings}.
  895. @end deftypefun
  896. Because these functions can abruptly truncate strings or wide strings,
  897. they are generally poor choices for processing text. When coping or
  898. concatening multibyte strings, they can truncate within a multibyte
  899. character so that the result is not a valid multibyte string. When
  900. combining or concatenating multibyte or wide strings, they may
  901. truncate the output after a combining character, resulting in a
  902. corrupted grapheme. They can cause bugs even when processing
  903. single-byte strings: for example, when calculating an ASCII-only user
  904. name, a truncated name can identify the wrong user.
  905. Although some buffer overruns can be prevented by manually replacing
  906. calls to copying functions with calls to truncation functions, there
  907. are often easier and safer automatic techniques that cause buffer
  908. overruns to reliably terminate a program, such as GCC's
  909. @option{-fcheck-pointer-bounds} and @option{-fsanitize=address}
  910. options. @xref{Debugging Options,, Options for Debugging Your Program
  911. or GCC, gcc, Using GCC}. Because truncation functions can mask
  912. application bugs that would otherwise be caught by the automatic
  913. techniques, these functions should be used only when the application's
  914. underlying logic requires truncation.
  915. @strong{Note:} GNU programs should not truncate strings or wide
  916. strings to fit arbitrary size limits. @xref{Semantics, , Writing
  917. Robust Programs, standards, The GNU Coding Standards}. Instead of
  918. string-truncation functions, it is usually better to use dynamic
  919. memory allocation (@pxref{Unconstrained Allocation}) and functions
  920. such as @code{strdup} or @code{asprintf} to construct strings.
  921. @node String/Array Comparison
  922. @section String/Array Comparison
  923. @cindex comparing strings and arrays
  924. @cindex string comparison functions
  925. @cindex array comparison functions
  926. @cindex predicates on strings
  927. @cindex predicates on arrays
  928. You can use the functions in this section to perform comparisons on the
  929. contents of strings and arrays. As well as checking for equality, these
  930. functions can also be used as the ordering functions for sorting
  931. operations. @xref{Searching and Sorting}, for an example of this.
  932. Unlike most comparison operations in C, the string comparison functions
  933. return a nonzero value if the strings are @emph{not} equivalent rather
  934. than if they are. The sign of the value indicates the relative ordering
  935. of the first part of the strings that are not equivalent: a
  936. negative value indicates that the first string is ``less'' than the
  937. second, while a positive value indicates that the first string is
  938. ``greater''.
  939. The most common use of these functions is to check only for equality.
  940. This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
  941. All of these functions are declared in the header file @file{string.h}.
  942. @pindex string.h
  943. @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
  944. @standards{ISO, string.h}
  945. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  946. The function @code{memcmp} compares the @var{size} bytes of memory
  947. beginning at @var{a1} against the @var{size} bytes of memory beginning
  948. at @var{a2}. The value returned has the same sign as the difference
  949. between the first differing pair of bytes (interpreted as @code{unsigned
  950. char} objects, then promoted to @code{int}).
  951. If the contents of the two blocks are equal, @code{memcmp} returns
  952. @code{0}.
  953. @end deftypefun
  954. @deftypefun int wmemcmp (const wchar_t *@var{a1}, const wchar_t *@var{a2}, size_t @var{size})
  955. @standards{ISO, wchar.h}
  956. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  957. The function @code{wmemcmp} compares the @var{size} wide characters
  958. beginning at @var{a1} against the @var{size} wide characters beginning
  959. at @var{a2}. The value returned is smaller than or larger than zero
  960. depending on whether the first differing wide character is @var{a1} is
  961. smaller or larger than the corresponding wide character in @var{a2}.
  962. If the contents of the two blocks are equal, @code{wmemcmp} returns
  963. @code{0}.
  964. @end deftypefun
  965. On arbitrary arrays, the @code{memcmp} function is mostly useful for
  966. testing equality. It usually isn't meaningful to do byte-wise ordering
  967. comparisons on arrays of things other than bytes. For example, a
  968. byte-wise comparison on the bytes that make up floating-point numbers
  969. isn't likely to tell you anything about the relationship between the
  970. values of the floating-point numbers.
  971. @code{wmemcmp} is really only useful to compare arrays of type
  972. @code{wchar_t} since the function looks at @code{sizeof (wchar_t)} bytes
  973. at a time and this number of bytes is system dependent.
  974. You should also be careful about using @code{memcmp} to compare objects
  975. that can contain ``holes'', such as the padding inserted into structure
  976. objects to enforce alignment requirements, extra space at the end of
  977. unions, and extra bytes at the ends of strings whose length is less
  978. than their allocated size. The contents of these ``holes'' are
  979. indeterminate and may cause strange behavior when performing byte-wise
  980. comparisons. For more predictable results, perform an explicit
  981. component-wise comparison.
  982. For example, given a structure type definition like:
  983. @smallexample
  984. struct foo
  985. @{
  986. unsigned char tag;
  987. union
  988. @{
  989. double f;
  990. long i;
  991. char *p;
  992. @} value;
  993. @};
  994. @end smallexample
  995. @noindent
  996. you are better off writing a specialized comparison function to compare
  997. @code{struct foo} objects instead of comparing them with @code{memcmp}.
  998. @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
  999. @standards{ISO, string.h}
  1000. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1001. The @code{strcmp} function compares the string @var{s1} against
  1002. @var{s2}, returning a value that has the same sign as the difference
  1003. between the first differing pair of bytes (interpreted as
  1004. @code{unsigned char} objects, then promoted to @code{int}).
  1005. If the two strings are equal, @code{strcmp} returns @code{0}.
  1006. A consequence of the ordering used by @code{strcmp} is that if @var{s1}
  1007. is an initial substring of @var{s2}, then @var{s1} is considered to be
  1008. ``less than'' @var{s2}.
  1009. @code{strcmp} does not take sorting conventions of the language the
  1010. strings are written in into account. To get that one has to use
  1011. @code{strcoll}.
  1012. @end deftypefun
  1013. @deftypefun int wcscmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
  1014. @standards{ISO, wchar.h}
  1015. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1016. The @code{wcscmp} function compares the wide string @var{ws1}
  1017. against @var{ws2}. The value returned is smaller than or larger than zero
  1018. depending on whether the first differing wide character is @var{ws1} is
  1019. smaller or larger than the corresponding wide character in @var{ws2}.
  1020. If the two strings are equal, @code{wcscmp} returns @code{0}.
  1021. A consequence of the ordering used by @code{wcscmp} is that if @var{ws1}
  1022. is an initial substring of @var{ws2}, then @var{ws1} is considered to be
  1023. ``less than'' @var{ws2}.
  1024. @code{wcscmp} does not take sorting conventions of the language the
  1025. strings are written in into account. To get that one has to use
  1026. @code{wcscoll}.
  1027. @end deftypefun
  1028. @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
  1029. @standards{BSD, string.h}
  1030. @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
  1031. @c Although this calls tolower multiple times, it's a macro, and
  1032. @c strcasecmp is optimized so that the locale pointer is read only once.
  1033. @c There are some asm implementations too, for which the single-read
  1034. @c from locale TLS pointers also applies.
  1035. This function is like @code{strcmp}, except that differences in case are
  1036. ignored, and its arguments must be multibyte strings.
  1037. How uppercase and lowercase characters are related is
  1038. determined by the currently selected locale. In the standard @code{"C"}
  1039. locale the characters @"A and @"a do not match but in a locale which
  1040. regards these characters as parts of the alphabet they do match.
  1041. @noindent
  1042. @code{strcasecmp} is derived from BSD.
  1043. @end deftypefun
  1044. @deftypefun int wcscasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
  1045. @standards{GNU, wchar.h}
  1046. @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
  1047. @c Since towlower is not a macro, the locale object may be read multiple
  1048. @c times.
  1049. This function is like @code{wcscmp}, except that differences in case are
  1050. ignored. How uppercase and lowercase characters are related is
  1051. determined by the currently selected locale. In the standard @code{"C"}
  1052. locale the characters @"A and @"a do not match but in a locale which
  1053. regards these characters as parts of the alphabet they do match.
  1054. @noindent
  1055. @code{wcscasecmp} is a GNU extension.
  1056. @end deftypefun
  1057. @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
  1058. @standards{ISO, string.h}
  1059. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1060. This function is the similar to @code{strcmp}, except that no more than
  1061. @var{size} bytes are compared. In other words, if the two
  1062. strings are the same in their first @var{size} bytes, the
  1063. return value is zero.
  1064. @end deftypefun
  1065. @deftypefun int wcsncmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2}, size_t @var{size})
  1066. @standards{ISO, wchar.h}
  1067. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1068. This function is similar to @code{wcscmp}, except that no more than
  1069. @var{size} wide characters are compared. In other words, if the two
  1070. strings are the same in their first @var{size} wide characters, the
  1071. return value is zero.
  1072. @end deftypefun
  1073. @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
  1074. @standards{BSD, string.h}
  1075. @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
  1076. This function is like @code{strncmp}, except that differences in case
  1077. are ignored, and the compared parts of the arguments should consist of
  1078. valid multibyte characters.
  1079. Like @code{strcasecmp}, it is locale dependent how
  1080. uppercase and lowercase characters are related.
  1081. @noindent
  1082. @code{strncasecmp} is a GNU extension.
  1083. @end deftypefun
  1084. @deftypefun int wcsncasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{s2}, size_t @var{n})
  1085. @standards{GNU, wchar.h}
  1086. @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
  1087. This function is like @code{wcsncmp}, except that differences in case
  1088. are ignored. Like @code{wcscasecmp}, it is locale dependent how
  1089. uppercase and lowercase characters are related.
  1090. @noindent
  1091. @code{wcsncasecmp} is a GNU extension.
  1092. @end deftypefun
  1093. Here are some examples showing the use of @code{strcmp} and
  1094. @code{strncmp} (equivalent examples can be constructed for the wide
  1095. character functions). These examples assume the use of the ASCII
  1096. character set. (If some other character set---say, EBCDIC---is used
  1097. instead, then the glyphs are associated with different numeric codes,
  1098. and the return values and ordering may differ.)
  1099. @smallexample
  1100. strcmp ("hello", "hello")
  1101. @result{} 0 /* @r{These two strings are the same.} */
  1102. strcmp ("hello", "Hello")
  1103. @result{} 32 /* @r{Comparisons are case-sensitive.} */
  1104. strcmp ("hello", "world")
  1105. @result{} -15 /* @r{The byte @code{'h'} comes before @code{'w'}.} */
  1106. strcmp ("hello", "hello, world")
  1107. @result{} -44 /* @r{Comparing a null byte against a comma.} */
  1108. strncmp ("hello", "hello, world", 5)
  1109. @result{} 0 /* @r{The initial 5 bytes are the same.} */
  1110. strncmp ("hello, world", "hello, stupid world!!!", 5)
  1111. @result{} 0 /* @r{The initial 5 bytes are the same.} */
  1112. @end smallexample
  1113. @deftypefun int strverscmp (const char *@var{s1}, const char *@var{s2})
  1114. @standards{GNU, string.h}
  1115. @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
  1116. @c Calls isdigit multiple times, locale may change in between.
  1117. The @code{strverscmp} function compares the string @var{s1} against
  1118. @var{s2}, considering them as holding indices/version numbers. The
  1119. return value follows the same conventions as found in the
  1120. @code{strcmp} function. In fact, if @var{s1} and @var{s2} contain no
  1121. digits, @code{strverscmp} behaves like @code{strcmp}
  1122. (in the sense that the sign of the result is the same).
  1123. The comparison algorithm which the @code{strverscmp} function implements
  1124. differs slightly from other version-comparison algorithms. The
  1125. implementation is based on a finite-state machine, whose behavior is
  1126. approximated below.
  1127. @itemize @bullet
  1128. @item
  1129. The input strings are each split into sequences of non-digits and
  1130. digits. These sequences can be empty at the beginning and end of the
  1131. string. Digits are determined by the @code{isdigit} function and are
  1132. thus subject to the current locale.
  1133. @item
  1134. Comparison starts with a (possibly empty) non-digit sequence. The first
  1135. non-equal sequences of non-digits or digits determines the outcome of
  1136. the comparison.
  1137. @item
  1138. Corresponding non-digit sequences in both strings are compared
  1139. lexicographically if their lengths are equal. If the lengths differ,
  1140. the shorter non-digit sequence is extended with the input string
  1141. character immediately following it (which may be the null terminator),
  1142. the other sequence is truncated to be of the same (extended) length, and
  1143. these two sequences are compared lexicographically. In the last case,
  1144. the sequence comparison determines the result of the function because
  1145. the extension character (or some character before it) is necessarily
  1146. different from the character at the same offset in the other input
  1147. string.
  1148. @item
  1149. For two sequences of digits, the number of leading zeros is counted (which
  1150. can be zero). If the count differs, the string with more leading zeros
  1151. in the digit sequence is considered smaller than the other string.
  1152. @item
  1153. If the two sequences of digits have no leading zeros, they are compared
  1154. as integers, that is, the string with the longer digit sequence is
  1155. deemed larger, and if both sequences are of equal length, they are
  1156. compared lexicographically.
  1157. @item
  1158. If both digit sequences start with a zero and have an equal number of
  1159. leading zeros, they are compared lexicographically if their lengths are
  1160. the same. If the lengths differ, the shorter sequence is extended with
  1161. the following character in its input string, and the other sequence is
  1162. truncated to the same length, and both sequences are compared
  1163. lexicographically (similar to the non-digit sequence case above).
  1164. @end itemize
  1165. The treatment of leading zeros and the tie-breaking extension characters
  1166. (which in effect propagate across non-digit/digit sequence boundaries)
  1167. differs from other version-comparison algorithms.
  1168. @smallexample
  1169. strverscmp ("no digit", "no digit")
  1170. @result{} 0 /* @r{same behavior as strcmp.} */
  1171. strverscmp ("item#99", "item#100")
  1172. @result{} <0 /* @r{same prefix, but 99 < 100.} */
  1173. strverscmp ("alpha1", "alpha001")
  1174. @result{} >0 /* @r{different number of leading zeros (0 and 2).} */
  1175. strverscmp ("part1_f012", "part1_f01")
  1176. @result{} >0 /* @r{lexicographical comparison with leading zeros.} */
  1177. strverscmp ("foo.009", "foo.0")
  1178. @result{} <0 /* @r{different number of leading zeros (2 and 1).} */
  1179. @end smallexample
  1180. @code{strverscmp} is a GNU extension.
  1181. @end deftypefun
  1182. @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
  1183. @standards{BSD, string.h}
  1184. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1185. This is an obsolete alias for @code{memcmp}, derived from BSD.
  1186. @end deftypefun
  1187. @node Collation Functions
  1188. @section Collation Functions
  1189. @cindex collating strings
  1190. @cindex string collation functions
  1191. In some locales, the conventions for lexicographic ordering differ from
  1192. the strict numeric ordering of character codes. For example, in Spanish
  1193. most glyphs with diacritical marks such as accents are not considered
  1194. distinct letters for the purposes of collation. On the other hand, the
  1195. two-character sequence @samp{ll} is treated as a single letter that is
  1196. collated immediately after @samp{l}.
  1197. You can use the functions @code{strcoll} and @code{strxfrm} (declared in
  1198. the headers file @file{string.h}) and @code{wcscoll} and @code{wcsxfrm}
  1199. (declared in the headers file @file{wchar}) to compare strings using a
  1200. collation ordering appropriate for the current locale. The locale used
  1201. by these functions in particular can be specified by setting the locale
  1202. for the @code{LC_COLLATE} category; see @ref{Locales}.
  1203. @pindex string.h
  1204. @pindex wchar.h
  1205. In the standard C locale, the collation sequence for @code{strcoll} is
  1206. the same as that for @code{strcmp}. Similarly, @code{wcscoll} and
  1207. @code{wcscmp} are the same in this situation.
  1208. Effectively, the way these functions work is by applying a mapping to
  1209. transform the characters in a multibyte string to a byte
  1210. sequence that represents
  1211. the string's position in the collating sequence of the current locale.
  1212. Comparing two such byte sequences in a simple fashion is equivalent to
  1213. comparing the strings with the locale's collating sequence.
  1214. The functions @code{strcoll} and @code{wcscoll} perform this translation
  1215. implicitly, in order to do one comparison. By contrast, @code{strxfrm}
  1216. and @code{wcsxfrm} perform the mapping explicitly. If you are making
  1217. multiple comparisons using the same string or set of strings, it is
  1218. likely to be more efficient to use @code{strxfrm} or @code{wcsxfrm} to
  1219. transform all the strings just once, and subsequently compare the
  1220. transformed strings with @code{strcmp} or @code{wcscmp}.
  1221. @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
  1222. @standards{ISO, string.h}
  1223. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  1224. @c Calls strcoll_l with the current locale, which dereferences only the
  1225. @c LC_COLLATE data pointer.
  1226. The @code{strcoll} function is similar to @code{strcmp} but uses the
  1227. collating sequence of the current locale for collation (the
  1228. @code{LC_COLLATE} locale). The arguments are multibyte strings.
  1229. @end deftypefun
  1230. @deftypefun int wcscoll (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
  1231. @standards{ISO, wchar.h}
  1232. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  1233. @c Same as strcoll, but calling wcscoll_l.
  1234. The @code{wcscoll} function is similar to @code{wcscmp} but uses the
  1235. collating sequence of the current locale for collation (the
  1236. @code{LC_COLLATE} locale).
  1237. @end deftypefun
  1238. Here is an example of sorting an array of strings, using @code{strcoll}
  1239. to compare them. The actual sort algorithm is not written here; it
  1240. comes from @code{qsort} (@pxref{Array Sort Function}). The job of the
  1241. code shown here is to say how to compare the strings while sorting them.
  1242. (Later on in this section, we will show a way to do this more
  1243. efficiently using @code{strxfrm}.)
  1244. @smallexample
  1245. /* @r{This is the comparison function used with @code{qsort}.} */
  1246. int
  1247. compare_elements (const void *v1, const void *v2)
  1248. @{
  1249. char * const *p1 = v1;
  1250. char * const *p2 = v2;
  1251. return strcoll (*p1, *p2);
  1252. @}
  1253. /* @r{This is the entry point---the function to sort}
  1254. @r{strings using the locale's collating sequence.} */
  1255. void
  1256. sort_strings (char **array, int nstrings)
  1257. @{
  1258. /* @r{Sort @code{temp_array} by comparing the strings.} */
  1259. qsort (array, nstrings,
  1260. sizeof (char *), compare_elements);
  1261. @}
  1262. @end smallexample
  1263. @cindex converting string to collation order
  1264. @deftypefun size_t strxfrm (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
  1265. @standards{ISO, string.h}
  1266. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  1267. The function @code{strxfrm} transforms the multibyte string
  1268. @var{from} using the
  1269. collation transformation determined by the locale currently selected for
  1270. collation, and stores the transformed string in the array @var{to}. Up
  1271. to @var{size} bytes (including a terminating null byte) are
  1272. stored.
  1273. The behavior is undefined if the strings @var{to} and @var{from}
  1274. overlap; see @ref{Copying Strings and Arrays}.
  1275. The return value is the length of the entire transformed string. This
  1276. value is not affected by the value of @var{size}, but if it is greater
  1277. or equal than @var{size}, it means that the transformed string did not
  1278. entirely fit in the array @var{to}. In this case, only as much of the
  1279. string as actually fits was stored. To get the whole transformed
  1280. string, call @code{strxfrm} again with a bigger output array.
  1281. The transformed string may be longer than the original string, and it
  1282. may also be shorter.
  1283. If @var{size} is zero, no bytes are stored in @var{to}. In this
  1284. case, @code{strxfrm} simply returns the number of bytes that would
  1285. be the length of the transformed string. This is useful for determining
  1286. what size the allocated array should be. It does not matter what
  1287. @var{to} is if @var{size} is zero; @var{to} may even be a null pointer.
  1288. @end deftypefun
  1289. @deftypefun size_t wcsxfrm (wchar_t *restrict @var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
  1290. @standards{ISO, wchar.h}
  1291. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  1292. The function @code{wcsxfrm} transforms wide string @var{wfrom}
  1293. using the collation transformation determined by the locale currently
  1294. selected for collation, and stores the transformed string in the array
  1295. @var{wto}. Up to @var{size} wide characters (including a terminating null
  1296. wide character) are stored.
  1297. The behavior is undefined if the strings @var{wto} and @var{wfrom}
  1298. overlap; see @ref{Copying Strings and Arrays}.
  1299. The return value is the length of the entire transformed wide
  1300. string. This value is not affected by the value of @var{size}, but if
  1301. it is greater or equal than @var{size}, it means that the transformed
  1302. wide string did not entirely fit in the array @var{wto}. In
  1303. this case, only as much of the wide string as actually fits
  1304. was stored. To get the whole transformed wide string, call
  1305. @code{wcsxfrm} again with a bigger output array.
  1306. The transformed wide string may be longer than the original
  1307. wide string, and it may also be shorter.
  1308. If @var{size} is zero, no wide characters are stored in @var{to}. In this
  1309. case, @code{wcsxfrm} simply returns the number of wide characters that
  1310. would be the length of the transformed wide string. This is
  1311. useful for determining what size the allocated array should be (remember
  1312. to multiply with @code{sizeof (wchar_t)}). It does not matter what
  1313. @var{wto} is if @var{size} is zero; @var{wto} may even be a null pointer.
  1314. @end deftypefun
  1315. Here is an example of how you can use @code{strxfrm} when
  1316. you plan to do many comparisons. It does the same thing as the previous
  1317. example, but much faster, because it has to transform each string only
  1318. once, no matter how many times it is compared with other strings. Even
  1319. the time needed to allocate and free storage is much less than the time
  1320. we save, when there are many strings.
  1321. @smallexample
  1322. struct sorter @{ char *input; char *transformed; @};
  1323. /* @r{This is the comparison function used with @code{qsort}}
  1324. @r{to sort an array of @code{struct sorter}.} */
  1325. int
  1326. compare_elements (const void *v1, const void *v2)
  1327. @{
  1328. const struct sorter *p1 = v1;
  1329. const struct sorter *p2 = v2;
  1330. return strcmp (p1->transformed, p2->transformed);
  1331. @}
  1332. /* @r{This is the entry point---the function to sort}
  1333. @r{strings using the locale's collating sequence.} */
  1334. void
  1335. sort_strings_fast (char **array, int nstrings)
  1336. @{
  1337. struct sorter temp_array[nstrings];
  1338. int i;
  1339. /* @r{Set up @code{temp_array}. Each element contains}
  1340. @r{one input string and its transformed string.} */
  1341. for (i = 0; i < nstrings; i++)
  1342. @{
  1343. size_t length = strlen (array[i]) * 2;
  1344. char *transformed;
  1345. size_t transformed_length;
  1346. temp_array[i].input = array[i];
  1347. /* @r{First try a buffer perhaps big enough.} */
  1348. transformed = (char *) xmalloc (length);
  1349. /* @r{Transform @code{array[i]}.} */
  1350. transformed_length = strxfrm (transformed, array[i], length);
  1351. /* @r{If the buffer was not large enough, resize it}
  1352. @r{and try again.} */
  1353. if (transformed_length >= length)
  1354. @{
  1355. /* @r{Allocate the needed space. +1 for terminating}
  1356. @r{@code{'\0'} byte.} */
  1357. transformed = (char *) xrealloc (transformed,
  1358. transformed_length + 1);
  1359. /* @r{The return value is not interesting because we know}
  1360. @r{how long the transformed string is.} */
  1361. (void) strxfrm (transformed, array[i],
  1362. transformed_length + 1);
  1363. @}
  1364. temp_array[i].transformed = transformed;
  1365. @}
  1366. /* @r{Sort @code{temp_array} by comparing transformed strings.} */
  1367. qsort (temp_array, nstrings,
  1368. sizeof (struct sorter), compare_elements);
  1369. /* @r{Put the elements back in the permanent array}
  1370. @r{in their sorted order.} */
  1371. for (i = 0; i < nstrings; i++)
  1372. array[i] = temp_array[i].input;
  1373. /* @r{Free the strings we allocated.} */
  1374. for (i = 0; i < nstrings; i++)
  1375. free (temp_array[i].transformed);
  1376. @}
  1377. @end smallexample
  1378. The interesting part of this code for the wide character version would
  1379. look like this:
  1380. @smallexample
  1381. void
  1382. sort_strings_fast (wchar_t **array, int nstrings)
  1383. @{
  1384. @dots{}
  1385. /* @r{Transform @code{array[i]}.} */
  1386. transformed_length = wcsxfrm (transformed, array[i], length);
  1387. /* @r{If the buffer was not large enough, resize it}
  1388. @r{and try again.} */
  1389. if (transformed_length >= length)
  1390. @{
  1391. /* @r{Allocate the needed space. +1 for terminating}
  1392. @r{@code{L'\0'} wide character.} */
  1393. transformed = (wchar_t *) xrealloc (transformed,
  1394. (transformed_length + 1)
  1395. * sizeof (wchar_t));
  1396. /* @r{The return value is not interesting because we know}
  1397. @r{how long the transformed string is.} */
  1398. (void) wcsxfrm (transformed, array[i],
  1399. transformed_length + 1);
  1400. @}
  1401. @dots{}
  1402. @end smallexample
  1403. @noindent
  1404. Note the additional multiplication with @code{sizeof (wchar_t)} in the
  1405. @code{realloc} call.
  1406. @strong{Compatibility Note:} The string collation functions are a new
  1407. feature of @w{ISO C90}. Older C dialects have no equivalent feature.
  1408. The wide character versions were introduced in @w{Amendment 1} to @w{ISO
  1409. C90}.
  1410. @node Search Functions
  1411. @section Search Functions
  1412. This section describes library functions which perform various kinds
  1413. of searching operations on strings and arrays. These functions are
  1414. declared in the header file @file{string.h}.
  1415. @pindex string.h
  1416. @cindex search functions (for strings)
  1417. @cindex string search functions
  1418. @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
  1419. @standards{ISO, string.h}
  1420. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1421. This function finds the first occurrence of the byte @var{c} (converted
  1422. to an @code{unsigned char}) in the initial @var{size} bytes of the
  1423. object beginning at @var{block}. The return value is a pointer to the
  1424. located byte, or a null pointer if no match was found.
  1425. @end deftypefun
  1426. @deftypefun {wchar_t *} wmemchr (const wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
  1427. @standards{ISO, wchar.h}
  1428. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1429. This function finds the first occurrence of the wide character @var{wc}
  1430. in the initial @var{size} wide characters of the object beginning at
  1431. @var{block}. The return value is a pointer to the located wide
  1432. character, or a null pointer if no match was found.
  1433. @end deftypefun
  1434. @deftypefun {void *} rawmemchr (const void *@var{block}, int @var{c})
  1435. @standards{GNU, string.h}
  1436. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1437. Often the @code{memchr} function is used with the knowledge that the
  1438. byte @var{c} is available in the memory block specified by the
  1439. parameters. But this means that the @var{size} parameter is not really
  1440. needed and that the tests performed with it at runtime (to check whether
  1441. the end of the block is reached) are not needed.
  1442. The @code{rawmemchr} function exists for just this situation which is
  1443. surprisingly frequent. The interface is similar to @code{memchr} except
  1444. that the @var{size} parameter is missing. The function will look beyond
  1445. the end of the block pointed to by @var{block} in case the programmer
  1446. made an error in assuming that the byte @var{c} is present in the block.
  1447. In this case the result is unspecified. Otherwise the return value is a
  1448. pointer to the located byte.
  1449. This function is of special interest when looking for the end of a
  1450. string. Since all strings are terminated by a null byte a call like
  1451. @smallexample
  1452. rawmemchr (str, '\0')
  1453. @end smallexample
  1454. @noindent
  1455. will never go beyond the end of the string.
  1456. This function is a GNU extension.
  1457. @end deftypefun
  1458. @deftypefun {void *} memrchr (const void *@var{block}, int @var{c}, size_t @var{size})
  1459. @standards{GNU, string.h}
  1460. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1461. The function @code{memrchr} is like @code{memchr}, except that it searches
  1462. backwards from the end of the block defined by @var{block} and @var{size}
  1463. (instead of forwards from the front).
  1464. This function is a GNU extension.
  1465. @end deftypefun
  1466. @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
  1467. @standards{ISO, string.h}
  1468. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1469. The @code{strchr} function finds the first occurrence of the byte
  1470. @var{c} (converted to a @code{char}) in the string
  1471. beginning at @var{string}. The return value is a pointer to the located
  1472. byte, or a null pointer if no match was found.
  1473. For example,
  1474. @smallexample
  1475. strchr ("hello, world", 'l')
  1476. @result{} "llo, world"
  1477. strchr ("hello, world", '?')
  1478. @result{} NULL
  1479. @end smallexample
  1480. The terminating null byte is considered to be part of the string,
  1481. so you can use this function get a pointer to the end of a string by
  1482. specifying zero as the value of the @var{c} argument.
  1483. When @code{strchr} returns a null pointer, it does not let you know
  1484. the position of the terminating null byte it has found. If you
  1485. need that information, it is better (but less portable) to use
  1486. @code{strchrnul} than to search for it a second time.
  1487. @end deftypefun
  1488. @deftypefun {wchar_t *} wcschr (const wchar_t *@var{wstring}, int @var{wc})
  1489. @standards{ISO, wchar.h}
  1490. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1491. The @code{wcschr} function finds the first occurrence of the wide
  1492. character @var{wc} in the wide string
  1493. beginning at @var{wstring}. The return value is a pointer to the
  1494. located wide character, or a null pointer if no match was found.
  1495. The terminating null wide character is considered to be part of the wide
  1496. string, so you can use this function get a pointer to the end
  1497. of a wide string by specifying a null wide character as the
  1498. value of the @var{wc} argument. It would be better (but less portable)
  1499. to use @code{wcschrnul} in this case, though.
  1500. @end deftypefun
  1501. @deftypefun {char *} strchrnul (const char *@var{string}, int @var{c})
  1502. @standards{GNU, string.h}
  1503. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1504. @code{strchrnul} is the same as @code{strchr} except that if it does
  1505. not find the byte, it returns a pointer to string's terminating
  1506. null byte rather than a null pointer.
  1507. This function is a GNU extension.
  1508. @end deftypefun
  1509. @deftypefun {wchar_t *} wcschrnul (const wchar_t *@var{wstring}, wchar_t @var{wc})
  1510. @standards{GNU, wchar.h}
  1511. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1512. @code{wcschrnul} is the same as @code{wcschr} except that if it does not
  1513. find the wide character, it returns a pointer to the wide string's
  1514. terminating null wide character rather than a null pointer.
  1515. This function is a GNU extension.
  1516. @end deftypefun
  1517. One useful, but unusual, use of the @code{strchr}
  1518. function is when one wants to have a pointer pointing to the null byte
  1519. terminating a string. This is often written in this way:
  1520. @smallexample
  1521. s += strlen (s);
  1522. @end smallexample
  1523. @noindent
  1524. This is almost optimal but the addition operation duplicated a bit of
  1525. the work already done in the @code{strlen} function. A better solution
  1526. is this:
  1527. @smallexample
  1528. s = strchr (s, '\0');
  1529. @end smallexample
  1530. There is no restriction on the second parameter of @code{strchr} so it
  1531. could very well also be zero. Those readers thinking very
  1532. hard about this might now point out that the @code{strchr} function is
  1533. more expensive than the @code{strlen} function since we have two abort
  1534. criteria. This is right. But in @theglibc{} the implementation of
  1535. @code{strchr} is optimized in a special way so that @code{strchr}
  1536. actually is faster.
  1537. @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
  1538. @standards{ISO, string.h}
  1539. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1540. The function @code{strrchr} is like @code{strchr}, except that it searches
  1541. backwards from the end of the string @var{string} (instead of forwards
  1542. from the front).
  1543. For example,
  1544. @smallexample
  1545. strrchr ("hello, world", 'l')
  1546. @result{} "ld"
  1547. @end smallexample
  1548. @end deftypefun
  1549. @deftypefun {wchar_t *} wcsrchr (const wchar_t *@var{wstring}, wchar_t @var{c})
  1550. @standards{ISO, wchar.h}
  1551. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1552. The function @code{wcsrchr} is like @code{wcschr}, except that it searches
  1553. backwards from the end of the string @var{wstring} (instead of forwards
  1554. from the front).
  1555. @end deftypefun
  1556. @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
  1557. @standards{ISO, string.h}
  1558. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1559. This is like @code{strchr}, except that it searches @var{haystack} for a
  1560. substring @var{needle} rather than just a single byte. It
  1561. returns a pointer into the string @var{haystack} that is the first
  1562. byte of the substring, or a null pointer if no match was found. If
  1563. @var{needle} is an empty string, the function returns @var{haystack}.
  1564. For example,
  1565. @smallexample
  1566. strstr ("hello, world", "l")
  1567. @result{} "llo, world"
  1568. strstr ("hello, world", "wo")
  1569. @result{} "world"
  1570. @end smallexample
  1571. @end deftypefun
  1572. @deftypefun {wchar_t *} wcsstr (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
  1573. @standards{ISO, wchar.h}
  1574. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1575. This is like @code{wcschr}, except that it searches @var{haystack} for a
  1576. substring @var{needle} rather than just a single wide character. It
  1577. returns a pointer into the string @var{haystack} that is the first wide
  1578. character of the substring, or a null pointer if no match was found. If
  1579. @var{needle} is an empty string, the function returns @var{haystack}.
  1580. @end deftypefun
  1581. @deftypefun {wchar_t *} wcswcs (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
  1582. @standards{XPG, wchar.h}
  1583. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1584. @code{wcswcs} is a deprecated alias for @code{wcsstr}. This is the
  1585. name originally used in the X/Open Portability Guide before the
  1586. @w{Amendment 1} to @w{ISO C90} was published.
  1587. @end deftypefun
  1588. @deftypefun {char *} strcasestr (const char *@var{haystack}, const char *@var{needle})
  1589. @standards{GNU, string.h}
  1590. @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
  1591. @c There may be multiple calls of strncasecmp, each accessing the locale
  1592. @c object independently.
  1593. This is like @code{strstr}, except that it ignores case in searching for
  1594. the substring. Like @code{strcasecmp}, it is locale dependent how
  1595. uppercase and lowercase characters are related, and arguments are
  1596. multibyte strings.
  1597. For example,
  1598. @smallexample
  1599. strcasestr ("hello, world", "L")
  1600. @result{} "llo, world"
  1601. strcasestr ("hello, World", "wo")
  1602. @result{} "World"
  1603. @end smallexample
  1604. @end deftypefun
  1605. @deftypefun {void *} memmem (const void *@var{haystack}, size_t @var{haystack-len},@*const void *@var{needle}, size_t @var{needle-len})
  1606. @standards{GNU, string.h}
  1607. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1608. This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
  1609. arrays rather than strings. @var{needle-len} is the
  1610. length of @var{needle} and @var{haystack-len} is the length of
  1611. @var{haystack}.@refill
  1612. This function is a GNU extension.
  1613. @end deftypefun
  1614. @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
  1615. @standards{ISO, string.h}
  1616. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1617. The @code{strspn} (``string span'') function returns the length of the
  1618. initial substring of @var{string} that consists entirely of bytes that
  1619. are members of the set specified by the string @var{skipset}. The order
  1620. of the bytes in @var{skipset} is not important.
  1621. For example,
  1622. @smallexample
  1623. strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
  1624. @result{} 5
  1625. @end smallexample
  1626. In a multibyte string, characters consisting of
  1627. more than one byte are not treated as single entities. Each byte is treated
  1628. separately. The function is not locale-dependent.
  1629. @end deftypefun
  1630. @deftypefun size_t wcsspn (const wchar_t *@var{wstring}, const wchar_t *@var{skipset})
  1631. @standards{ISO, wchar.h}
  1632. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1633. The @code{wcsspn} (``wide character string span'') function returns the
  1634. length of the initial substring of @var{wstring} that consists entirely
  1635. of wide characters that are members of the set specified by the string
  1636. @var{skipset}. The order of the wide characters in @var{skipset} is not
  1637. important.
  1638. @end deftypefun
  1639. @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
  1640. @standards{ISO, string.h}
  1641. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1642. The @code{strcspn} (``string complement span'') function returns the length
  1643. of the initial substring of @var{string} that consists entirely of bytes
  1644. that are @emph{not} members of the set specified by the string @var{stopset}.
  1645. (In other words, it returns the offset of the first byte in @var{string}
  1646. that is a member of the set @var{stopset}.)
  1647. For example,
  1648. @smallexample
  1649. strcspn ("hello, world", " \t\n,.;!?")
  1650. @result{} 5
  1651. @end smallexample
  1652. In a multibyte string, characters consisting of
  1653. more than one byte are not treated as a single entities. Each byte is treated
  1654. separately. The function is not locale-dependent.
  1655. @end deftypefun
  1656. @deftypefun size_t wcscspn (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
  1657. @standards{ISO, wchar.h}
  1658. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1659. The @code{wcscspn} (``wide character string complement span'') function
  1660. returns the length of the initial substring of @var{wstring} that
  1661. consists entirely of wide characters that are @emph{not} members of the
  1662. set specified by the string @var{stopset}. (In other words, it returns
  1663. the offset of the first wide character in @var{string} that is a member of
  1664. the set @var{stopset}.)
  1665. @end deftypefun
  1666. @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
  1667. @standards{ISO, string.h}
  1668. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1669. The @code{strpbrk} (``string pointer break'') function is related to
  1670. @code{strcspn}, except that it returns a pointer to the first byte
  1671. in @var{string} that is a member of the set @var{stopset} instead of the
  1672. length of the initial substring. It returns a null pointer if no such
  1673. byte from @var{stopset} is found.
  1674. @c @group Invalid outside the example.
  1675. For example,
  1676. @smallexample
  1677. strpbrk ("hello, world", " \t\n,.;!?")
  1678. @result{} ", world"
  1679. @end smallexample
  1680. @c @end group
  1681. In a multibyte string, characters consisting of
  1682. more than one byte are not treated as single entities. Each byte is treated
  1683. separately. The function is not locale-dependent.
  1684. @end deftypefun
  1685. @deftypefun {wchar_t *} wcspbrk (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
  1686. @standards{ISO, wchar.h}
  1687. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1688. The @code{wcspbrk} (``wide character string pointer break'') function is
  1689. related to @code{wcscspn}, except that it returns a pointer to the first
  1690. wide character in @var{wstring} that is a member of the set
  1691. @var{stopset} instead of the length of the initial substring. It
  1692. returns a null pointer if no such wide character from @var{stopset} is found.
  1693. @end deftypefun
  1694. @subsection Compatibility String Search Functions
  1695. @deftypefun {char *} index (const char *@var{string}, int @var{c})
  1696. @standards{BSD, string.h}
  1697. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1698. @code{index} is another name for @code{strchr}; they are exactly the same.
  1699. New code should always use @code{strchr} since this name is defined in
  1700. @w{ISO C} while @code{index} is a BSD invention which never was available
  1701. on @w{System V} derived systems.
  1702. @end deftypefun
  1703. @deftypefun {char *} rindex (const char *@var{string}, int @var{c})
  1704. @standards{BSD, string.h}
  1705. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1706. @code{rindex} is another name for @code{strrchr}; they are exactly the same.
  1707. New code should always use @code{strrchr} since this name is defined in
  1708. @w{ISO C} while @code{rindex} is a BSD invention which never was available
  1709. on @w{System V} derived systems.
  1710. @end deftypefun
  1711. @node Finding Tokens in a String
  1712. @section Finding Tokens in a String
  1713. @cindex tokenizing strings
  1714. @cindex breaking a string into tokens
  1715. @cindex parsing tokens from a string
  1716. It's fairly common for programs to have a need to do some simple kinds
  1717. of lexical analysis and parsing, such as splitting a command string up
  1718. into tokens. You can do this with the @code{strtok} function, declared
  1719. in the header file @file{string.h}.
  1720. @pindex string.h
  1721. @deftypefun {char *} strtok (char *restrict @var{newstring}, const char *restrict @var{delimiters})
  1722. @standards{ISO, string.h}
  1723. @safety{@prelim{}@mtunsafe{@mtasurace{:strtok}}@asunsafe{}@acsafe{}}
  1724. A string can be split into tokens by making a series of calls to the
  1725. function @code{strtok}.
  1726. The string to be split up is passed as the @var{newstring} argument on
  1727. the first call only. The @code{strtok} function uses this to set up
  1728. some internal state information. Subsequent calls to get additional
  1729. tokens from the same string are indicated by passing a null pointer as
  1730. the @var{newstring} argument. Calling @code{strtok} with another
  1731. non-null @var{newstring} argument reinitializes the state information.
  1732. It is guaranteed that no other library function ever calls @code{strtok}
  1733. behind your back (which would mess up this internal state information).
  1734. The @var{delimiters} argument is a string that specifies a set of delimiters
  1735. that may surround the token being extracted. All the initial bytes
  1736. that are members of this set are discarded. The first byte that is
  1737. @emph{not} a member of this set of delimiters marks the beginning of the
  1738. next token. The end of the token is found by looking for the next
  1739. byte that is a member of the delimiter set. This byte in the
  1740. original string @var{newstring} is overwritten by a null byte, and the
  1741. pointer to the beginning of the token in @var{newstring} is returned.
  1742. On the next call to @code{strtok}, the searching begins at the next
  1743. byte beyond the one that marked the end of the previous token.
  1744. Note that the set of delimiters @var{delimiters} do not have to be the
  1745. same on every call in a series of calls to @code{strtok}.
  1746. If the end of the string @var{newstring} is reached, or if the remainder of
  1747. string consists only of delimiter bytes, @code{strtok} returns
  1748. a null pointer.
  1749. In a multibyte string, characters consisting of
  1750. more than one byte are not treated as single entities. Each byte is treated
  1751. separately. The function is not locale-dependent.
  1752. @end deftypefun
  1753. @deftypefun {wchar_t *} wcstok (wchar_t *@var{newstring}, const wchar_t *@var{delimiters}, wchar_t **@var{save_ptr})
  1754. @standards{ISO, wchar.h}
  1755. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1756. A string can be split into tokens by making a series of calls to the
  1757. function @code{wcstok}.
  1758. The string to be split up is passed as the @var{newstring} argument on
  1759. the first call only. The @code{wcstok} function uses this to set up
  1760. some internal state information. Subsequent calls to get additional
  1761. tokens from the same wide string are indicated by passing a
  1762. null pointer as the @var{newstring} argument, which causes the pointer
  1763. previously stored in @var{save_ptr} to be used instead.
  1764. The @var{delimiters} argument is a wide string that specifies
  1765. a set of delimiters that may surround the token being extracted. All
  1766. the initial wide characters that are members of this set are discarded.
  1767. The first wide character that is @emph{not} a member of this set of
  1768. delimiters marks the beginning of the next token. The end of the token
  1769. is found by looking for the next wide character that is a member of the
  1770. delimiter set. This wide character in the original wide
  1771. string @var{newstring} is overwritten by a null wide character, the
  1772. pointer past the overwritten wide character is saved in @var{save_ptr},
  1773. and the pointer to the beginning of the token in @var{newstring} is
  1774. returned.
  1775. On the next call to @code{wcstok}, the searching begins at the next
  1776. wide character beyond the one that marked the end of the previous token.
  1777. Note that the set of delimiters @var{delimiters} do not have to be the
  1778. same on every call in a series of calls to @code{wcstok}.
  1779. If the end of the wide string @var{newstring} is reached, or
  1780. if the remainder of string consists only of delimiter wide characters,
  1781. @code{wcstok} returns a null pointer.
  1782. @end deftypefun
  1783. @strong{Warning:} Since @code{strtok} and @code{wcstok} alter the string
  1784. they is parsing, you should always copy the string to a temporary buffer
  1785. before parsing it with @code{strtok}/@code{wcstok} (@pxref{Copying Strings
  1786. and Arrays}). If you allow @code{strtok} or @code{wcstok} to modify
  1787. a string that came from another part of your program, you are asking for
  1788. trouble; that string might be used for other purposes after
  1789. @code{strtok} or @code{wcstok} has modified it, and it would not have
  1790. the expected value.
  1791. The string that you are operating on might even be a constant. Then
  1792. when @code{strtok} or @code{wcstok} tries to modify it, your program
  1793. will get a fatal signal for writing in read-only memory. @xref{Program
  1794. Error Signals}. Even if the operation of @code{strtok} or @code{wcstok}
  1795. would not require a modification of the string (e.g., if there is
  1796. exactly one token) the string can (and in the @glibcadj{} case will) be
  1797. modified.
  1798. This is a special case of a general principle: if a part of a program
  1799. does not have as its purpose the modification of a certain data
  1800. structure, then it is error-prone to modify the data structure
  1801. temporarily.
  1802. The function @code{strtok} is not reentrant, whereas @code{wcstok} is.
  1803. @xref{Nonreentrancy}, for a discussion of where and why reentrancy is
  1804. important.
  1805. Here is a simple example showing the use of @code{strtok}.
  1806. @comment Yes, this example has been tested.
  1807. @smallexample
  1808. #include <string.h>
  1809. #include <stddef.h>
  1810. @dots{}
  1811. const char string[] = "words separated by spaces -- and, punctuation!";
  1812. const char delimiters[] = " .,;:!-";
  1813. char *token, *cp;
  1814. @dots{}
  1815. cp = strdupa (string); /* Make writable copy. */
  1816. token = strtok (cp, delimiters); /* token => "words" */
  1817. token = strtok (NULL, delimiters); /* token => "separated" */
  1818. token = strtok (NULL, delimiters); /* token => "by" */
  1819. token = strtok (NULL, delimiters); /* token => "spaces" */
  1820. token = strtok (NULL, delimiters); /* token => "and" */
  1821. token = strtok (NULL, delimiters); /* token => "punctuation" */
  1822. token = strtok (NULL, delimiters); /* token => NULL */
  1823. @end smallexample
  1824. @Theglibc{} contains two more functions for tokenizing a string
  1825. which overcome the limitation of non-reentrancy. They are not
  1826. available available for wide strings.
  1827. @deftypefun {char *} strtok_r (char *@var{newstring}, const char *@var{delimiters}, char **@var{save_ptr})
  1828. @standards{POSIX, string.h}
  1829. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1830. Just like @code{strtok}, this function splits the string into several
  1831. tokens which can be accessed by successive calls to @code{strtok_r}.
  1832. The difference is that, as in @code{wcstok}, the information about the
  1833. next token is stored in the space pointed to by the third argument,
  1834. @var{save_ptr}, which is a pointer to a string pointer. Calling
  1835. @code{strtok_r} with a null pointer for @var{newstring} and leaving
  1836. @var{save_ptr} between the calls unchanged does the job without
  1837. hindering reentrancy.
  1838. This function is defined in POSIX.1 and can be found on many systems
  1839. which support multi-threading.
  1840. @end deftypefun
  1841. @deftypefun {char *} strsep (char **@var{string_ptr}, const char *@var{delimiter})
  1842. @standards{BSD, string.h}
  1843. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1844. This function has a similar functionality as @code{strtok_r} with the
  1845. @var{newstring} argument replaced by the @var{save_ptr} argument. The
  1846. initialization of the moving pointer has to be done by the user.
  1847. Successive calls to @code{strsep} move the pointer along the tokens
  1848. separated by @var{delimiter}, returning the address of the next token
  1849. and updating @var{string_ptr} to point to the beginning of the next
  1850. token.
  1851. One difference between @code{strsep} and @code{strtok_r} is that if the
  1852. input string contains more than one byte from @var{delimiter} in a
  1853. row @code{strsep} returns an empty string for each pair of bytes
  1854. from @var{delimiter}. This means that a program normally should test
  1855. for @code{strsep} returning an empty string before processing it.
  1856. This function was introduced in 4.3BSD and therefore is widely available.
  1857. @end deftypefun
  1858. Here is how the above example looks like when @code{strsep} is used.
  1859. @comment Yes, this example has been tested.
  1860. @smallexample
  1861. #include <string.h>
  1862. #include <stddef.h>
  1863. @dots{}
  1864. const char string[] = "words separated by spaces -- and, punctuation!";
  1865. const char delimiters[] = " .,;:!-";
  1866. char *running;
  1867. char *token;
  1868. @dots{}
  1869. running = strdupa (string);
  1870. token = strsep (&running, delimiters); /* token => "words" */
  1871. token = strsep (&running, delimiters); /* token => "separated" */
  1872. token = strsep (&running, delimiters); /* token => "by" */
  1873. token = strsep (&running, delimiters); /* token => "spaces" */
  1874. token = strsep (&running, delimiters); /* token => "" */
  1875. token = strsep (&running, delimiters); /* token => "" */
  1876. token = strsep (&running, delimiters); /* token => "" */
  1877. token = strsep (&running, delimiters); /* token => "and" */
  1878. token = strsep (&running, delimiters); /* token => "" */
  1879. token = strsep (&running, delimiters); /* token => "punctuation" */
  1880. token = strsep (&running, delimiters); /* token => "" */
  1881. token = strsep (&running, delimiters); /* token => NULL */
  1882. @end smallexample
  1883. @deftypefun {char *} basename (const char *@var{filename})
  1884. @standards{GNU, string.h}
  1885. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1886. The GNU version of the @code{basename} function returns the last
  1887. component of the path in @var{filename}. This function is the preferred
  1888. usage, since it does not modify the argument, @var{filename}, and
  1889. respects trailing slashes. The prototype for @code{basename} can be
  1890. found in @file{string.h}. Note, this function is overridden by the XPG
  1891. version, if @file{libgen.h} is included.
  1892. Example of using GNU @code{basename}:
  1893. @smallexample
  1894. #include <string.h>
  1895. int
  1896. main (int argc, char *argv[])
  1897. @{
  1898. char *prog = basename (argv[0]);
  1899. if (argc < 2)
  1900. @{
  1901. fprintf (stderr, "Usage %s <arg>\n", prog);
  1902. exit (1);
  1903. @}
  1904. @dots{}
  1905. @}
  1906. @end smallexample
  1907. @strong{Portability Note:} This function may produce different results
  1908. on different systems.
  1909. @end deftypefun
  1910. @deftypefun {char *} basename (char *@var{path})
  1911. @standards{XPG, libgen.h}
  1912. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1913. This is the standard XPG defined @code{basename}. It is similar in
  1914. spirit to the GNU version, but may modify the @var{path} by removing
  1915. trailing '/' bytes. If the @var{path} is made up entirely of '/'
  1916. bytes, then "/" will be returned. Also, if @var{path} is
  1917. @code{NULL} or an empty string, then "." is returned. The prototype for
  1918. the XPG version can be found in @file{libgen.h}.
  1919. Example of using XPG @code{basename}:
  1920. @smallexample
  1921. #include <libgen.h>
  1922. int
  1923. main (int argc, char *argv[])
  1924. @{
  1925. char *prog;
  1926. char *path = strdupa (argv[0]);
  1927. prog = basename (path);
  1928. if (argc < 2)
  1929. @{
  1930. fprintf (stderr, "Usage %s <arg>\n", prog);
  1931. exit (1);
  1932. @}
  1933. @dots{}
  1934. @}
  1935. @end smallexample
  1936. @end deftypefun
  1937. @deftypefun {char *} dirname (char *@var{path})
  1938. @standards{XPG, libgen.h}
  1939. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1940. The @code{dirname} function is the compliment to the XPG version of
  1941. @code{basename}. It returns the parent directory of the file specified
  1942. by @var{path}. If @var{path} is @code{NULL}, an empty string, or
  1943. contains no '/' bytes, then "." is returned. The prototype for this
  1944. function can be found in @file{libgen.h}.
  1945. @end deftypefun
  1946. @node Erasing Sensitive Data
  1947. @section Erasing Sensitive Data
  1948. Sensitive data, such as cryptographic keys, should be erased from
  1949. memory after use, to reduce the risk that a bug will expose it to the
  1950. outside world. However, compiler optimizations may determine that an
  1951. erasure operation is ``unnecessary,'' and remove it from the generated
  1952. code, because no @emph{correct} program could access the variable or
  1953. heap object containing the sensitive data after it's deallocated.
  1954. Since erasure is a precaution against bugs, this optimization is
  1955. inappropriate.
  1956. The function @code{explicit_bzero} erases a block of memory, and
  1957. guarantees that the compiler will not remove the erasure as
  1958. ``unnecessary.''
  1959. @smallexample
  1960. @group
  1961. #include <string.h>
  1962. extern void encrypt (const char *key, const char *in,
  1963. char *out, size_t n);
  1964. extern void genkey (const char *phrase, char *key);
  1965. void encrypt_with_phrase (const char *phrase, const char *in,
  1966. char *out, size_t n)
  1967. @{
  1968. char key[16];
  1969. genkey (phrase, key);
  1970. encrypt (key, in, out, n);
  1971. explicit_bzero (key, 16);
  1972. @}
  1973. @end group
  1974. @end smallexample
  1975. @noindent
  1976. In this example, if @code{memset}, @code{bzero}, or a hand-written
  1977. loop had been used, the compiler might remove them as ``unnecessary.''
  1978. @strong{Warning:} @code{explicit_bzero} does not guarantee that
  1979. sensitive data is @emph{completely} erased from the computer's memory.
  1980. There may be copies in temporary storage areas, such as registers and
  1981. ``scratch'' stack space; since these are invisible to the source code,
  1982. a library function cannot erase them.
  1983. Also, @code{explicit_bzero} only operates on RAM. If a sensitive data
  1984. object never needs to have its address taken other than to call
  1985. @code{explicit_bzero}, it might be stored entirely in CPU registers
  1986. @emph{until} the call to @code{explicit_bzero}. Then it will be
  1987. copied into RAM, the copy will be erased, and the original will remain
  1988. intact. Data in RAM is more likely to be exposed by a bug than data
  1989. in registers, so this creates a brief window where the data is at
  1990. greater risk of exposure than it would have been if the program didn't
  1991. try to erase it at all.
  1992. Declaring sensitive variables as @code{volatile} will make both the
  1993. above problems @emph{worse}; a @code{volatile} variable will be stored
  1994. in memory for its entire lifetime, and the compiler will make
  1995. @emph{more} copies of it than it would otherwise have. Attempting to
  1996. erase a normal variable ``by hand'' through a
  1997. @code{volatile}-qualified pointer doesn't work at all---because the
  1998. variable itself is not @code{volatile}, some compilers will ignore the
  1999. qualification on the pointer and remove the erasure anyway.
  2000. Having said all that, in most situations, using @code{explicit_bzero}
  2001. is better than not using it. At present, the only way to do a more
  2002. thorough job is to write the entire sensitive operation in assembly
  2003. language. We anticipate that future compilers will recognize calls to
  2004. @code{explicit_bzero} and take appropriate steps to erase all the
  2005. copies of the affected data, whereever they may be.
  2006. @deftypefun void explicit_bzero (void *@var{block}, size_t @var{len})
  2007. @standards{BSD, string.h}
  2008. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2009. @code{explicit_bzero} writes zero into @var{len} bytes of memory
  2010. beginning at @var{block}, just as @code{bzero} would. The zeroes are
  2011. always written, even if the compiler could determine that this is
  2012. ``unnecessary'' because no correct program could read them back.
  2013. @strong{Note:} The @emph{only} optimization that @code{explicit_bzero}
  2014. disables is removal of ``unnecessary'' writes to memory. The compiler
  2015. can perform all the other optimizations that it could for a call to
  2016. @code{memset}. For instance, it may replace the function call with
  2017. inline memory writes, and it may assume that @var{block} cannot be a
  2018. null pointer.
  2019. @strong{Portability Note:} This function first appeared in OpenBSD 5.5
  2020. and has not been standardized. Other systems may provide the same
  2021. functionality under a different name, such as @code{explicit_memset},
  2022. @code{memset_s}, or @code{SecureZeroMemory}.
  2023. @Theglibc{} declares this function in @file{string.h}, but on other
  2024. systems it may be in @file{strings.h} instead.
  2025. @end deftypefun
  2026. @node Shuffling Bytes
  2027. @section Shuffling Bytes
  2028. The function below addresses the perennial programming quandary: ``How do
  2029. I take good data in string form and painlessly turn it into garbage?''
  2030. This is not a difficult thing to code for oneself, but the authors of
  2031. @theglibc{} wish to make it as convenient as possible.
  2032. To @emph{erase} data, use @code{explicit_bzero} (@pxref{Erasing
  2033. Sensitive Data}); to obfuscate it reversibly, use @code{memfrob}
  2034. (@pxref{Obfuscating Data}).
  2035. @deftypefun {char *} strfry (char *@var{string})
  2036. @standards{GNU, string.h}
  2037. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2038. @c Calls initstate_r, time, getpid, strlen, and random_r.
  2039. @code{strfry} performs an in-place shuffle on @var{string}. Each
  2040. character is swapped to a position selected at random, within the
  2041. portion of the string starting with the character's original position.
  2042. (This is the Fisher-Yates algorithm for unbiased shuffling.)
  2043. Calling @code{strfry} will not disturb any of the random number
  2044. generators that have global state (@pxref{Pseudo-Random Numbers}).
  2045. The return value of @code{strfry} is always @var{string}.
  2046. @strong{Portability Note:} This function is unique to @theglibc{}.
  2047. It is declared in @file{string.h}.
  2048. @end deftypefun
  2049. @node Obfuscating Data
  2050. @section Obfuscating Data
  2051. @cindex Rot13
  2052. The @code{memfrob} function reversibly obfuscates an array of binary
  2053. data. This is not true encryption; the obfuscated data still bears a
  2054. clear relationship to the original, and no secret key is required to
  2055. undo the obfuscation. It is analogous to the ``Rot13'' cipher used on
  2056. Usenet for obscuring offensive jokes, spoilers for works of fiction,
  2057. and so on, but it can be applied to arbitrary binary data.
  2058. Programs that need true encryption---a transformation that completely
  2059. obscures the original and cannot be reversed without knowledge of a
  2060. secret key---should use a dedicated cryptography library, such as
  2061. @uref{https://www.gnu.org/software/libgcrypt/,,libgcrypt}.
  2062. Programs that need to @emph{destroy} data should use
  2063. @code{explicit_bzero} (@pxref{Erasing Sensitive Data}), or possibly
  2064. @code{strfry} (@pxref{Shuffling Bytes}).
  2065. @deftypefun {void *} memfrob (void *@var{mem}, size_t @var{length})
  2066. @standards{GNU, string.h}
  2067. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2068. The function @code{memfrob} obfuscates @var{length} bytes of data
  2069. beginning at @var{mem}, in place. Each byte is bitwise xor-ed with
  2070. the binary pattern 00101010 (hexadecimal 0x2A). The return value is
  2071. always @var{mem}.
  2072. @code{memfrob} a second time on the same data returns it to
  2073. its original state.
  2074. @strong{Portability Note:} This function is unique to @theglibc{}.
  2075. It is declared in @file{string.h}.
  2076. @end deftypefun
  2077. @node Encode Binary Data
  2078. @section Encode Binary Data
  2079. To store or transfer binary data in environments which only support text
  2080. one has to encode the binary data by mapping the input bytes to
  2081. bytes in the range allowed for storing or transferring. SVID
  2082. systems (and nowadays XPG compliant systems) provide minimal support for
  2083. this task.
  2084. @deftypefun {char *} l64a (long int @var{n})
  2085. @standards{XPG, stdlib.h}
  2086. @safety{@prelim{}@mtunsafe{@mtasurace{:l64a}}@asunsafe{}@acsafe{}}
  2087. This function encodes a 32-bit input value using bytes from the
  2088. basic character set. It returns a pointer to a 7 byte buffer which
  2089. contains an encoded version of @var{n}. To encode a series of bytes the
  2090. user must copy the returned string to a destination buffer. It returns
  2091. the empty string if @var{n} is zero, which is somewhat bizarre but
  2092. mandated by the standard.@*
  2093. @strong{Warning:} Since a static buffer is used this function should not
  2094. be used in multi-threaded programs. There is no thread-safe alternative
  2095. to this function in the C library.@*
  2096. @strong{Compatibility Note:} The XPG standard states that the return
  2097. value of @code{l64a} is undefined if @var{n} is negative. In the GNU
  2098. implementation, @code{l64a} treats its argument as unsigned, so it will
  2099. return a sensible encoding for any nonzero @var{n}; however, portable
  2100. programs should not rely on this.
  2101. To encode a large buffer @code{l64a} must be called in a loop, once for
  2102. each 32-bit word of the buffer. For example, one could do something
  2103. like this:
  2104. @smallexample
  2105. char *
  2106. encode (const void *buf, size_t len)
  2107. @{
  2108. /* @r{We know in advance how long the buffer has to be.} */
  2109. unsigned char *in = (unsigned char *) buf;
  2110. char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
  2111. char *cp = out, *p;
  2112. /* @r{Encode the length.} */
  2113. /* @r{Using `htonl' is necessary so that the data can be}
  2114. @r{decoded even on machines with different byte order.}
  2115. @r{`l64a' can return a string shorter than 6 bytes, so }
  2116. @r{we pad it with encoding of 0 (}'.'@r{) at the end by }
  2117. @r{hand.} */
  2118. p = stpcpy (cp, l64a (htonl (len)));
  2119. cp = mempcpy (p, "......", 6 - (p - cp));
  2120. while (len > 3)
  2121. @{
  2122. unsigned long int n = *in++;
  2123. n = (n << 8) | *in++;
  2124. n = (n << 8) | *in++;
  2125. n = (n << 8) | *in++;
  2126. len -= 4;
  2127. p = stpcpy (cp, l64a (htonl (n)));
  2128. cp = mempcpy (p, "......", 6 - (p - cp));
  2129. @}
  2130. if (len > 0)
  2131. @{
  2132. unsigned long int n = *in++;
  2133. if (--len > 0)
  2134. @{
  2135. n = (n << 8) | *in++;
  2136. if (--len > 0)
  2137. n = (n << 8) | *in;
  2138. @}
  2139. cp = stpcpy (cp, l64a (htonl (n)));
  2140. @}
  2141. *cp = '\0';
  2142. return out;
  2143. @}
  2144. @end smallexample
  2145. It is strange that the library does not provide the complete
  2146. functionality needed but so be it.
  2147. @end deftypefun
  2148. To decode data produced with @code{l64a} the following function should be
  2149. used.
  2150. @deftypefun {long int} a64l (const char *@var{string})
  2151. @standards{XPG, stdlib.h}
  2152. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2153. The parameter @var{string} should contain a string which was produced by
  2154. a call to @code{l64a}. The function processes at least 6 bytes of
  2155. this string, and decodes the bytes it finds according to the table
  2156. below. It stops decoding when it finds a byte not in the table,
  2157. rather like @code{atoi}; if you have a buffer which has been broken into
  2158. lines, you must be careful to skip over the end-of-line bytes.
  2159. The decoded number is returned as a @code{long int} value.
  2160. @end deftypefun
  2161. The @code{l64a} and @code{a64l} functions use a base 64 encoding, in
  2162. which each byte of an encoded string represents six bits of an
  2163. input word. These symbols are used for the base 64 digits:
  2164. @multitable {xxxxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx}
  2165. @item @tab 0 @tab 1 @tab 2 @tab 3 @tab 4 @tab 5 @tab 6 @tab 7
  2166. @item 0 @tab @code{.} @tab @code{/} @tab @code{0} @tab @code{1}
  2167. @tab @code{2} @tab @code{3} @tab @code{4} @tab @code{5}
  2168. @item 8 @tab @code{6} @tab @code{7} @tab @code{8} @tab @code{9}
  2169. @tab @code{A} @tab @code{B} @tab @code{C} @tab @code{D}
  2170. @item 16 @tab @code{E} @tab @code{F} @tab @code{G} @tab @code{H}
  2171. @tab @code{I} @tab @code{J} @tab @code{K} @tab @code{L}
  2172. @item 24 @tab @code{M} @tab @code{N} @tab @code{O} @tab @code{P}
  2173. @tab @code{Q} @tab @code{R} @tab @code{S} @tab @code{T}
  2174. @item 32 @tab @code{U} @tab @code{V} @tab @code{W} @tab @code{X}
  2175. @tab @code{Y} @tab @code{Z} @tab @code{a} @tab @code{b}
  2176. @item 40 @tab @code{c} @tab @code{d} @tab @code{e} @tab @code{f}
  2177. @tab @code{g} @tab @code{h} @tab @code{i} @tab @code{j}
  2178. @item 48 @tab @code{k} @tab @code{l} @tab @code{m} @tab @code{n}
  2179. @tab @code{o} @tab @code{p} @tab @code{q} @tab @code{r}
  2180. @item 56 @tab @code{s} @tab @code{t} @tab @code{u} @tab @code{v}
  2181. @tab @code{w} @tab @code{x} @tab @code{y} @tab @code{z}
  2182. @end multitable
  2183. This encoding scheme is not standard. There are some other encoding
  2184. methods which are much more widely used (UU encoding, MIME encoding).
  2185. Generally, it is better to use one of these encodings.
  2186. @node Argz and Envz Vectors
  2187. @section Argz and Envz Vectors
  2188. @cindex argz vectors (string vectors)
  2189. @cindex string vectors, null-byte separated
  2190. @cindex argument vectors, null-byte separated
  2191. @dfn{argz vectors} are vectors of strings in a contiguous block of
  2192. memory, each element separated from its neighbors by null bytes
  2193. (@code{'\0'}).
  2194. @cindex envz vectors (environment vectors)
  2195. @cindex environment vectors, null-byte separated
  2196. @dfn{Envz vectors} are an extension of argz vectors where each element is a
  2197. name-value pair, separated by a @code{'='} byte (as in a Unix
  2198. environment).
  2199. @menu
  2200. * Argz Functions:: Operations on argz vectors.
  2201. * Envz Functions:: Additional operations on environment vectors.
  2202. @end menu
  2203. @node Argz Functions, Envz Functions, , Argz and Envz Vectors
  2204. @subsection Argz Functions
  2205. Each argz vector is represented by a pointer to the first element, of
  2206. type @code{char *}, and a size, of type @code{size_t}, both of which can
  2207. be initialized to @code{0} to represent an empty argz vector. All argz
  2208. functions accept either a pointer and a size argument, or pointers to
  2209. them, if they will be modified.
  2210. The argz functions use @code{malloc}/@code{realloc} to allocate/grow
  2211. argz vectors, and so any argz vector created using these functions may
  2212. be freed by using @code{free}; conversely, any argz function that may
  2213. grow a string expects that string to have been allocated using
  2214. @code{malloc} (those argz functions that only examine their arguments or
  2215. modify them in place will work on any sort of memory).
  2216. @xref{Unconstrained Allocation}.
  2217. All argz functions that do memory allocation have a return type of
  2218. @code{error_t}, and return @code{0} for success, and @code{ENOMEM} if an
  2219. allocation error occurs.
  2220. @pindex argz.h
  2221. These functions are declared in the standard include file @file{argz.h}.
  2222. @deftypefun {error_t} argz_create (char *const @var{argv}[], char **@var{argz}, size_t *@var{argz_len})
  2223. @standards{GNU, argz.h}
  2224. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2225. The @code{argz_create} function converts the Unix-style argument vector
  2226. @var{argv} (a vector of pointers to normal C strings, terminated by
  2227. @code{(char *)0}; @pxref{Program Arguments}) into an argz vector with
  2228. the same elements, which is returned in @var{argz} and @var{argz_len}.
  2229. @end deftypefun
  2230. @deftypefun {error_t} argz_create_sep (const char *@var{string}, int @var{sep}, char **@var{argz}, size_t *@var{argz_len})
  2231. @standards{GNU, argz.h}
  2232. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2233. The @code{argz_create_sep} function converts the string
  2234. @var{string} into an argz vector (returned in @var{argz} and
  2235. @var{argz_len}) by splitting it into elements at every occurrence of the
  2236. byte @var{sep}.
  2237. @end deftypefun
  2238. @deftypefun {size_t} argz_count (const char *@var{argz}, size_t @var{argz_len})
  2239. @standards{GNU, argz.h}
  2240. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2241. Returns the number of elements in the argz vector @var{argz} and
  2242. @var{argz_len}.
  2243. @end deftypefun
  2244. @deftypefun {void} argz_extract (const char *@var{argz}, size_t @var{argz_len}, char **@var{argv})
  2245. @standards{GNU, argz.h}
  2246. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2247. The @code{argz_extract} function converts the argz vector @var{argz} and
  2248. @var{argz_len} into a Unix-style argument vector stored in @var{argv},
  2249. by putting pointers to every element in @var{argz} into successive
  2250. positions in @var{argv}, followed by a terminator of @code{0}.
  2251. @var{Argv} must be pre-allocated with enough space to hold all the
  2252. elements in @var{argz} plus the terminating @code{(char *)0}
  2253. (@code{(argz_count (@var{argz}, @var{argz_len}) + 1) * sizeof (char *)}
  2254. bytes should be enough). Note that the string pointers stored into
  2255. @var{argv} point into @var{argz}---they are not copies---and so
  2256. @var{argz} must be copied if it will be changed while @var{argv} is
  2257. still active. This function is useful for passing the elements in
  2258. @var{argz} to an exec function (@pxref{Executing a File}).
  2259. @end deftypefun
  2260. @deftypefun {void} argz_stringify (char *@var{argz}, size_t @var{len}, int @var{sep})
  2261. @standards{GNU, argz.h}
  2262. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2263. The @code{argz_stringify} converts @var{argz} into a normal string with
  2264. the elements separated by the byte @var{sep}, by replacing each
  2265. @code{'\0'} inside @var{argz} (except the last one, which terminates the
  2266. string) with @var{sep}. This is handy for printing @var{argz} in a
  2267. readable manner.
  2268. @end deftypefun
  2269. @deftypefun {error_t} argz_add (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str})
  2270. @standards{GNU, argz.h}
  2271. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2272. @c Calls strlen and argz_append.
  2273. The @code{argz_add} function adds the string @var{str} to the end of the
  2274. argz vector @code{*@var{argz}}, and updates @code{*@var{argz}} and
  2275. @code{*@var{argz_len}} accordingly.
  2276. @end deftypefun
  2277. @deftypefun {error_t} argz_add_sep (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str}, int @var{delim})
  2278. @standards{GNU, argz.h}
  2279. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2280. The @code{argz_add_sep} function is similar to @code{argz_add}, but
  2281. @var{str} is split into separate elements in the result at occurrences of
  2282. the byte @var{delim}. This is useful, for instance, for
  2283. adding the components of a Unix search path to an argz vector, by using
  2284. a value of @code{':'} for @var{delim}.
  2285. @end deftypefun
  2286. @deftypefun {error_t} argz_append (char **@var{argz}, size_t *@var{argz_len}, const char *@var{buf}, size_t @var{buf_len})
  2287. @standards{GNU, argz.h}
  2288. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2289. The @code{argz_append} function appends @var{buf_len} bytes starting at
  2290. @var{buf} to the argz vector @code{*@var{argz}}, reallocating
  2291. @code{*@var{argz}} to accommodate it, and adding @var{buf_len} to
  2292. @code{*@var{argz_len}}.
  2293. @end deftypefun
  2294. @deftypefun {void} argz_delete (char **@var{argz}, size_t *@var{argz_len}, char *@var{entry})
  2295. @standards{GNU, argz.h}
  2296. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2297. @c Calls free if no argument is left.
  2298. If @var{entry} points to the beginning of one of the elements in the
  2299. argz vector @code{*@var{argz}}, the @code{argz_delete} function will
  2300. remove this entry and reallocate @code{*@var{argz}}, modifying
  2301. @code{*@var{argz}} and @code{*@var{argz_len}} accordingly. Note that as
  2302. destructive argz functions usually reallocate their argz argument,
  2303. pointers into argz vectors such as @var{entry} will then become invalid.
  2304. @end deftypefun
  2305. @deftypefun {error_t} argz_insert (char **@var{argz}, size_t *@var{argz_len}, char *@var{before}, const char *@var{entry})
  2306. @standards{GNU, argz.h}
  2307. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2308. @c Calls argz_add or realloc and memmove.
  2309. The @code{argz_insert} function inserts the string @var{entry} into the
  2310. argz vector @code{*@var{argz}} at a point just before the existing
  2311. element pointed to by @var{before}, reallocating @code{*@var{argz}} and
  2312. updating @code{*@var{argz}} and @code{*@var{argz_len}}. If @var{before}
  2313. is @code{0}, @var{entry} is added to the end instead (as if by
  2314. @code{argz_add}). Since the first element is in fact the same as
  2315. @code{*@var{argz}}, passing in @code{*@var{argz}} as the value of
  2316. @var{before} will result in @var{entry} being inserted at the beginning.
  2317. @end deftypefun
  2318. @deftypefun {char *} argz_next (const char *@var{argz}, size_t @var{argz_len}, const char *@var{entry})
  2319. @standards{GNU, argz.h}
  2320. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2321. The @code{argz_next} function provides a convenient way of iterating
  2322. over the elements in the argz vector @var{argz}. It returns a pointer
  2323. to the next element in @var{argz} after the element @var{entry}, or
  2324. @code{0} if there are no elements following @var{entry}. If @var{entry}
  2325. is @code{0}, the first element of @var{argz} is returned.
  2326. This behavior suggests two styles of iteration:
  2327. @smallexample
  2328. char *entry = 0;
  2329. while ((entry = argz_next (@var{argz}, @var{argz_len}, entry)))
  2330. @var{action};
  2331. @end smallexample
  2332. (the double parentheses are necessary to make some C compilers shut up
  2333. about what they consider a questionable @code{while}-test) and:
  2334. @smallexample
  2335. char *entry;
  2336. for (entry = @var{argz};
  2337. entry;
  2338. entry = argz_next (@var{argz}, @var{argz_len}, entry))
  2339. @var{action};
  2340. @end smallexample
  2341. Note that the latter depends on @var{argz} having a value of @code{0} if
  2342. it is empty (rather than a pointer to an empty block of memory); this
  2343. invariant is maintained for argz vectors created by the functions here.
  2344. @end deftypefun
  2345. @deftypefun error_t argz_replace (@w{char **@var{argz}, size_t *@var{argz_len}}, @w{const char *@var{str}, const char *@var{with}}, @w{unsigned *@var{replace_count}})
  2346. @standards{GNU, argz.h}
  2347. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2348. Replace any occurrences of the string @var{str} in @var{argz} with
  2349. @var{with}, reallocating @var{argz} as necessary. If
  2350. @var{replace_count} is non-zero, @code{*@var{replace_count}} will be
  2351. incremented by the number of replacements performed.
  2352. @end deftypefun
  2353. @node Envz Functions, , Argz Functions, Argz and Envz Vectors
  2354. @subsection Envz Functions
  2355. Envz vectors are just argz vectors with additional constraints on the form
  2356. of each element; as such, argz functions can also be used on them, where it
  2357. makes sense.
  2358. Each element in an envz vector is a name-value pair, separated by a @code{'='}
  2359. byte; if multiple @code{'='} bytes are present in an element, those
  2360. after the first are considered part of the value, and treated like all other
  2361. non-@code{'\0'} bytes.
  2362. If @emph{no} @code{'='} bytes are present in an element, that element is
  2363. considered the name of a ``null'' entry, as distinct from an entry with an
  2364. empty value: @code{envz_get} will return @code{0} if given the name of null
  2365. entry, whereas an entry with an empty value would result in a value of
  2366. @code{""}; @code{envz_entry} will still find such entries, however. Null
  2367. entries can be removed with the @code{envz_strip} function.
  2368. As with argz functions, envz functions that may allocate memory (and thus
  2369. fail) have a return type of @code{error_t}, and return either @code{0} or
  2370. @code{ENOMEM}.
  2371. @pindex envz.h
  2372. These functions are declared in the standard include file @file{envz.h}.
  2373. @deftypefun {char *} envz_entry (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
  2374. @standards{GNU, envz.h}
  2375. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2376. The @code{envz_entry} function finds the entry in @var{envz} with the name
  2377. @var{name}, and returns a pointer to the whole entry---that is, the argz
  2378. element which begins with @var{name} followed by a @code{'='} byte. If
  2379. there is no entry with that name, @code{0} is returned.
  2380. @end deftypefun
  2381. @deftypefun {char *} envz_get (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
  2382. @standards{GNU, envz.h}
  2383. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2384. The @code{envz_get} function finds the entry in @var{envz} with the name
  2385. @var{name} (like @code{envz_entry}), and returns a pointer to the value
  2386. portion of that entry (following the @code{'='}). If there is no entry with
  2387. that name (or only a null entry), @code{0} is returned.
  2388. @end deftypefun
  2389. @deftypefun {error_t} envz_add (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name}, const char *@var{value})
  2390. @standards{GNU, envz.h}
  2391. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2392. @c Calls envz_remove, which calls enz_entry and argz_delete, and then
  2393. @c argz_add or equivalent code that reallocs and appends name=value.
  2394. The @code{envz_add} function adds an entry to @code{*@var{envz}}
  2395. (updating @code{*@var{envz}} and @code{*@var{envz_len}}) with the name
  2396. @var{name}, and value @var{value}. If an entry with the same name
  2397. already exists in @var{envz}, it is removed first. If @var{value} is
  2398. @code{0}, then the new entry will be the special null type of entry
  2399. (mentioned above).
  2400. @end deftypefun
  2401. @deftypefun {error_t} envz_merge (char **@var{envz}, size_t *@var{envz_len}, const char *@var{envz2}, size_t @var{envz2_len}, int @var{override})
  2402. @standards{GNU, envz.h}
  2403. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2404. The @code{envz_merge} function adds each entry in @var{envz2} to @var{envz},
  2405. as if with @code{envz_add}, updating @code{*@var{envz}} and
  2406. @code{*@var{envz_len}}. If @var{override} is true, then values in @var{envz2}
  2407. will supersede those with the same name in @var{envz}, otherwise not.
  2408. Null entries are treated just like other entries in this respect, so a null
  2409. entry in @var{envz} can prevent an entry of the same name in @var{envz2} from
  2410. being added to @var{envz}, if @var{override} is false.
  2411. @end deftypefun
  2412. @deftypefun {void} envz_strip (char **@var{envz}, size_t *@var{envz_len})
  2413. @standards{GNU, envz.h}
  2414. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2415. The @code{envz_strip} function removes any null entries from @var{envz},
  2416. updating @code{*@var{envz}} and @code{*@var{envz_len}}.
  2417. @end deftypefun
  2418. @deftypefun {void} envz_remove (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name})
  2419. @standards{GNU, envz.h}
  2420. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2421. The @code{envz_remove} function removes an entry named @var{name} from
  2422. @var{envz}, updating @code{*@var{envz}} and @code{*@var{envz_len}}.
  2423. @end deftypefun
  2424. @c FIXME this are undocumented:
  2425. @c strcasecmp_l @safety{@mtsafe{}@assafe{}@acsafe{}} see strcasecmp