Add a testase for BZ #14602
[glibc.git] / manual / string.texi
blob2844bc61e5332f6fc6006fbbd1f28ff623b8c33f
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
5 Operations on strings (or arrays of characters) are an important part of
6 many programs.  @Theglibc{} provides an extensive set of string
7 utility functions, including functions for copying, concatenating,
8 comparing, and searching strings.  Many of these functions can also
9 operate on arbitrary regions of storage; for example, the @code{memcpy}
10 function can be used to copy the contents of any kind of array.
12 It's fairly common for beginning C programmers to ``reinvent the wheel''
13 by duplicating this functionality in their own code, but it pays to
14 become familiar with the library functions and to make use of them,
15 since this offers benefits in maintenance, efficiency, and portability.
17 For instance, you could easily compare one string to another in two
18 lines of C code, but if you use the built-in @code{strcmp} function,
19 you're less likely to make a mistake.  And, since these library
20 functions are typically highly optimized, your program may run faster
21 too.
23 @menu
24 * Representation of Strings::   Introduction to basic concepts.
25 * String/Array Conventions::    Whether to use a string function or an
26                                  arbitrary array function.
27 * String Length::               Determining the length of a string.
28 * Copying and Concatenation::   Functions to copy the contents of strings
29                                  and arrays.
30 * String/Array Comparison::     Functions for byte-wise and character-wise
31                                  comparison.
32 * Collation Functions::         Functions for collating strings.
33 * Search Functions::            Searching for a specific element or substring.
34 * Finding Tokens in a String::  Splitting a string into tokens by looking
35                                  for delimiters.
36 * strfry::                      Function for flash-cooking a string.
37 * Trivial Encryption::          Obscuring data.
38 * Encode Binary Data::          Encoding and Decoding of Binary Data.
39 * Argz and Envz Vectors::       Null-separated string vectors.
40 @end menu
42 @node Representation of Strings
43 @section Representation of Strings
44 @cindex string, representation of
46 This section is a quick summary of string concepts for beginning C
47 programmers.  It describes how character strings are represented in C
48 and some common pitfalls.  If you are already familiar with this
49 material, you can skip this section.
51 @cindex string
52 @cindex multibyte character string
53 A @dfn{string} is an array of @code{char} objects.  But string-valued
54 variables are usually declared to be pointers of type @code{char *}.
55 Such variables do not include space for the text of a string; that has
56 to be stored somewhere else---in an array variable, a string constant,
57 or dynamically allocated memory (@pxref{Memory Allocation}).  It's up to
58 you to store the address of the chosen memory space into the pointer
59 variable.  Alternatively you can store a @dfn{null pointer} in the
60 pointer variable.  The null pointer does not point anywhere, so
61 attempting to reference the string it points to gets an error.
63 @cindex wide character string
64 ``string'' normally refers to multibyte character strings as opposed to
65 wide character strings.  Wide character strings are arrays of type
66 @code{wchar_t} and as for multibyte character strings usually pointers
67 of type @code{wchar_t *} are used.
69 @cindex null character
70 @cindex null wide character
71 By convention, a @dfn{null character}, @code{'\0'}, marks the end of a
72 multibyte character string and the @dfn{null wide character},
73 @code{L'\0'}, marks the end of a wide character string.  For example, in
74 testing to see whether the @code{char *} variable @var{p} points to a
75 null character marking the end of a string, you can write
76 @code{!*@var{p}} or @code{*@var{p} == '\0'}.
78 A null character is quite different conceptually from a null pointer,
79 although both are represented by the integer @code{0}.
81 @cindex string literal
82 @dfn{String literals} appear in C program source as strings of
83 characters between double-quote characters (@samp{"}) where the initial
84 double-quote character is immediately preceded by a capital @samp{L}
85 (ell) character (as in @code{L"foo"}).  In @w{ISO C}, string literals
86 can also be formed by @dfn{string concatenation}: @code{"a" "b"} is the
87 same as @code{"ab"}.  For wide character strings one can either use
88 @code{L"a" L"b"} or @code{L"a" "b"}.  Modification of string literals is
89 not allowed by the GNU C compiler, because literals are placed in
90 read-only storage.
92 Character arrays that are declared @code{const} cannot be modified
93 either.  It's generally good style to declare non-modifiable string
94 pointers to be of type @code{const char *}, since this often allows the
95 C compiler to detect accidental modifications as well as providing some
96 amount of documentation about what your program intends to do with the
97 string.
99 The amount of memory allocated for the character array may extend past
100 the null character that normally marks the end of the string.  In this
101 document, the term @dfn{allocated size} is always used to refer to the
102 total amount of memory allocated for the string, while the term
103 @dfn{length} refers to the number of characters up to (but not
104 including) the terminating null character.
105 @cindex length of string
106 @cindex allocation size of string
107 @cindex size of string
108 @cindex string length
109 @cindex string allocation
111 A notorious source of program bugs is trying to put more characters in a
112 string than fit in its allocated size.  When writing code that extends
113 strings or moves characters into a pre-allocated array, you should be
114 very careful to keep track of the length of the text and make explicit
115 checks for overflowing the array.  Many of the library functions
116 @emph{do not} do this for you!  Remember also that you need to allocate
117 an extra byte to hold the null character that marks the end of the
118 string.
120 @cindex single-byte string
121 @cindex multibyte string
122 Originally strings were sequences of bytes where each byte represents a
123 single character.  This is still true today if the strings are encoded
124 using a single-byte character encoding.  Things are different if the
125 strings are encoded using a multibyte encoding (for more information on
126 encodings see @ref{Extended Char Intro}).  There is no difference in
127 the programming interface for these two kind of strings; the programmer
128 has to be aware of this and interpret the byte sequences accordingly.
130 But since there is no separate interface taking care of these
131 differences the byte-based string functions are sometimes hard to use.
132 Since the count parameters of these functions specify bytes a call to
133 @code{strncpy} could cut a multibyte character in the middle and put an
134 incomplete (and therefore unusable) byte sequence in the target buffer.
136 @cindex wide character string
137 To avoid these problems later versions of the @w{ISO C} standard
138 introduce a second set of functions which are operating on @dfn{wide
139 characters} (@pxref{Extended Char Intro}).  These functions don't have
140 the problems the single-byte versions have since every wide character is
141 a legal, interpretable value.  This does not mean that cutting wide
142 character strings at arbitrary points is without problems.  It normally
143 is for alphabet-based languages (except for non-normalized text) but
144 languages based on syllables still have the problem that more than one
145 wide character is necessary to complete a logical unit.  This is a
146 higher level problem which the @w{C library} functions are not designed
147 to solve.  But it is at least good that no invalid byte sequences can be
148 created.  Also, the higher level functions can also much easier operate
149 on wide character than on multibyte characters so that a general advise
150 is to use wide characters internally whenever text is more than simply
151 copied.
153 The remaining of this chapter will discuss the functions for handling
154 wide character strings in parallel with the discussion of the multibyte
155 character strings since there is almost always an exact equivalent
156 available.
158 @node String/Array Conventions
159 @section String and Array Conventions
161 This chapter describes both functions that work on arbitrary arrays or
162 blocks of memory, and functions that are specific to null-terminated
163 arrays of characters and wide characters.
165 Functions that operate on arbitrary blocks of memory have names
166 beginning with @samp{mem} and @samp{wmem} (such as @code{memcpy} and
167 @code{wmemcpy}) and invariably take an argument which specifies the size
168 (in bytes and wide characters respectively) of the block of memory to
169 operate on.  The array arguments and return values for these functions
170 have type @code{void *} or @code{wchar_t}.  As a matter of style, the
171 elements of the arrays used with the @samp{mem} functions are referred
172 to as ``bytes''.  You can pass any kind of pointer to these functions,
173 and the @code{sizeof} operator is useful in computing the value for the
174 size argument.  Parameters to the @samp{wmem} functions must be of type
175 @code{wchar_t *}.  These functions are not really usable with anything
176 but arrays of this type.
178 In contrast, functions that operate specifically on strings and wide
179 character strings have names beginning with @samp{str} and @samp{wcs}
180 respectively (such as @code{strcpy} and @code{wcscpy}) and look for a
181 null character to terminate the string instead of requiring an explicit
182 size argument to be passed.  (Some of these functions accept a specified
183 maximum length, but they also check for premature termination with a
184 null character.)  The array arguments and return values for these
185 functions have type @code{char *} and @code{wchar_t *} respectively, and
186 the array elements are referred to as ``characters'' and ``wide
187 characters''.
189 In many cases, there are both @samp{mem} and @samp{str}/@samp{wcs}
190 versions of a function.  The one that is more appropriate to use depends
191 on the exact situation.  When your program is manipulating arbitrary
192 arrays or blocks of storage, then you should always use the @samp{mem}
193 functions.  On the other hand, when you are manipulating null-terminated
194 strings it is usually more convenient to use the @samp{str}/@samp{wcs}
195 functions, unless you already know the length of the string in advance.
196 The @samp{wmem} functions should be used for wide character arrays with
197 known size.
199 @cindex wint_t
200 @cindex parameter promotion
201 Some of the memory and string functions take single characters as
202 arguments.  Since a value of type @code{char} is automatically promoted
203 into an value of type @code{int} when used as a parameter, the functions
204 are declared with @code{int} as the type of the parameter in question.
205 In case of the wide character function the situation is similarly: the
206 parameter type for a single wide character is @code{wint_t} and not
207 @code{wchar_t}.  This would for many implementations not be necessary
208 since the @code{wchar_t} is large enough to not be automatically
209 promoted, but since the @w{ISO C} standard does not require such a
210 choice of types the @code{wint_t} type is used.
212 @node String Length
213 @section String Length
215 You can get the length of a string using the @code{strlen} function.
216 This function is declared in the header file @file{string.h}.
217 @pindex string.h
219 @comment string.h
220 @comment ISO
221 @deftypefun size_t strlen (const char *@var{s})
222 The @code{strlen} function returns the length of the null-terminated
223 string @var{s} in bytes.  (In other words, it returns the offset of the
224 terminating null character within the array.)
226 For example,
227 @smallexample
228 strlen ("hello, world")
229     @result{} 12
230 @end smallexample
232 When applied to a character array, the @code{strlen} function returns
233 the length of the string stored there, not its allocated size.  You can
234 get the allocated size of the character array that holds a string using
235 the @code{sizeof} operator:
237 @smallexample
238 char string[32] = "hello, world";
239 sizeof (string)
240     @result{} 32
241 strlen (string)
242     @result{} 12
243 @end smallexample
245 But beware, this will not work unless @var{string} is the character
246 array itself, not a pointer to it.  For example:
248 @smallexample
249 char string[32] = "hello, world";
250 char *ptr = string;
251 sizeof (string)
252     @result{} 32
253 sizeof (ptr)
254     @result{} 4  /* @r{(on a machine with 4 byte pointers)} */
255 @end smallexample
257 This is an easy mistake to make when you are working with functions that
258 take string arguments; those arguments are always pointers, not arrays.
260 It must also be noted that for multibyte encoded strings the return
261 value does not have to correspond to the number of characters in the
262 string.  To get this value the string can be converted to wide
263 characters and @code{wcslen} can be used or something like the following
264 code can be used:
266 @smallexample
267 /* @r{The input is in @code{string}.}
268    @r{The length is expected in @code{n}.}  */
270   mbstate_t t;
271   char *scopy = string;
272   /* In initial state.  */
273   memset (&t, '\0', sizeof (t));
274   /* Determine number of characters.  */
275   n = mbsrtowcs (NULL, &scopy, strlen (scopy), &t);
277 @end smallexample
279 This is cumbersome to do so if the number of characters (as opposed to
280 bytes) is needed often it is better to work with wide characters.
281 @end deftypefun
283 The wide character equivalent is declared in @file{wchar.h}.
285 @comment wchar.h
286 @comment ISO
287 @deftypefun size_t wcslen (const wchar_t *@var{ws})
288 The @code{wcslen} function is the wide character equivalent to
289 @code{strlen}.  The return value is the number of wide characters in the
290 wide character string pointed to by @var{ws} (this is also the offset of
291 the terminating null wide character of @var{ws}).
293 Since there are no multi wide character sequences making up one
294 character the return value is not only the offset in the array, it is
295 also the number of wide characters.
297 This function was introduced in @w{Amendment 1} to @w{ISO C90}.
298 @end deftypefun
300 @comment string.h
301 @comment GNU
302 @deftypefun size_t strnlen (const char *@var{s}, size_t @var{maxlen})
303 The @code{strnlen} function returns the length of the string @var{s} in
304 bytes if this length is smaller than @var{maxlen} bytes.  Otherwise it
305 returns @var{maxlen}.  Therefore this function is equivalent to
306 @code{(strlen (@var{s}) < @var{maxlen} ? strlen (@var{s}) : @var{maxlen})}
307 but it
308 is more efficient and works even if the string @var{s} is not
309 null-terminated.
311 @smallexample
312 char string[32] = "hello, world";
313 strnlen (string, 32)
314     @result{} 12
315 strnlen (string, 5)
316     @result{} 5
317 @end smallexample
319 This function is a GNU extension and is declared in @file{string.h}.
320 @end deftypefun
322 @comment wchar.h
323 @comment GNU
324 @deftypefun size_t wcsnlen (const wchar_t *@var{ws}, size_t @var{maxlen})
325 @code{wcsnlen} is the wide character equivalent to @code{strnlen}.  The
326 @var{maxlen} parameter specifies the maximum number of wide characters.
328 This function is a GNU extension and is declared in @file{wchar.h}.
329 @end deftypefun
331 @node Copying and Concatenation
332 @section Copying and Concatenation
334 You can use the functions described in this section to copy the contents
335 of strings and arrays, or to append the contents of one string to
336 another.  The @samp{str} and @samp{mem} functions are declared in the
337 header file @file{string.h} while the @samp{wstr} and @samp{wmem}
338 functions are declared in the file @file{wchar.h}.
339 @pindex string.h
340 @pindex wchar.h
341 @cindex copying strings and arrays
342 @cindex string copy functions
343 @cindex array copy functions
344 @cindex concatenating strings
345 @cindex string concatenation functions
347 A helpful way to remember the ordering of the arguments to the functions
348 in this section is that it corresponds to an assignment expression, with
349 the destination array specified to the left of the source array.  All
350 of these functions return the address of the destination array.
352 Most of these functions do not work properly if the source and
353 destination arrays overlap.  For example, if the beginning of the
354 destination array overlaps the end of the source array, the original
355 contents of that part of the source array may get overwritten before it
356 is copied.  Even worse, in the case of the string functions, the null
357 character marking the end of the string may be lost, and the copy
358 function might get stuck in a loop trashing all the memory allocated to
359 your program.
361 All functions that have problems copying between overlapping arrays are
362 explicitly identified in this manual.  In addition to functions in this
363 section, there are a few others like @code{sprintf} (@pxref{Formatted
364 Output Functions}) and @code{scanf} (@pxref{Formatted Input
365 Functions}).
367 @comment string.h
368 @comment ISO
369 @deftypefun {void *} memcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
370 The @code{memcpy} function copies @var{size} bytes from the object
371 beginning at @var{from} into the object beginning at @var{to}.  The
372 behavior of this function is undefined if the two arrays @var{to} and
373 @var{from} overlap; use @code{memmove} instead if overlapping is possible.
375 The value returned by @code{memcpy} is the value of @var{to}.
377 Here is an example of how you might use @code{memcpy} to copy the
378 contents of an array:
380 @smallexample
381 struct foo *oldarray, *newarray;
382 int arraysize;
383 @dots{}
384 memcpy (new, old, arraysize * sizeof (struct foo));
385 @end smallexample
386 @end deftypefun
388 @comment wchar.h
389 @comment ISO
390 @deftypefun {wchar_t *} wmemcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
391 The @code{wmemcpy} function copies @var{size} wide characters from the object
392 beginning at @var{wfrom} into the object beginning at @var{wto}.  The
393 behavior of this function is undefined if the two arrays @var{wto} and
394 @var{wfrom} overlap; use @code{wmemmove} instead if overlapping is possible.
396 The following is a possible implementation of @code{wmemcpy} but there
397 are more optimizations possible.
399 @smallexample
400 wchar_t *
401 wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
402          size_t size)
404   return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));
406 @end smallexample
408 The value returned by @code{wmemcpy} is the value of @var{wto}.
410 This function was introduced in @w{Amendment 1} to @w{ISO C90}.
411 @end deftypefun
413 @comment string.h
414 @comment GNU
415 @deftypefun {void *} mempcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
416 The @code{mempcpy} function is nearly identical to the @code{memcpy}
417 function.  It copies @var{size} bytes from the object beginning at
418 @code{from} into the object pointed to by @var{to}.  But instead of
419 returning the value of @var{to} it returns a pointer to the byte
420 following the last written byte in the object beginning at @var{to}.
421 I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
423 This function is useful in situations where a number of objects shall be
424 copied to consecutive memory positions.
426 @smallexample
427 void *
428 combine (void *o1, size_t s1, void *o2, size_t s2)
430   void *result = malloc (s1 + s2);
431   if (result != NULL)
432     mempcpy (mempcpy (result, o1, s1), o2, s2);
433   return result;
435 @end smallexample
437 This function is a GNU extension.
438 @end deftypefun
440 @comment wchar.h
441 @comment GNU
442 @deftypefun {wchar_t *} wmempcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
443 The @code{wmempcpy} function is nearly identical to the @code{wmemcpy}
444 function.  It copies @var{size} wide characters from the object
445 beginning at @code{wfrom} into the object pointed to by @var{wto}.  But
446 instead of returning the value of @var{wto} it returns a pointer to the
447 wide character following the last written wide character in the object
448 beginning at @var{wto}.  I.e., the value is @code{@var{wto} + @var{size}}.
450 This function is useful in situations where a number of objects shall be
451 copied to consecutive memory positions.
453 The following is a possible implementation of @code{wmemcpy} but there
454 are more optimizations possible.
456 @smallexample
457 wchar_t *
458 wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
459           size_t size)
461   return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
463 @end smallexample
465 This function is a GNU extension.
466 @end deftypefun
468 @comment string.h
469 @comment ISO
470 @deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
471 @code{memmove} copies the @var{size} bytes at @var{from} into the
472 @var{size} bytes at @var{to}, even if those two blocks of space
473 overlap.  In the case of overlap, @code{memmove} is careful to copy the
474 original values of the bytes in the block at @var{from}, including those
475 bytes which also belong to the block at @var{to}.
477 The value returned by @code{memmove} is the value of @var{to}.
478 @end deftypefun
480 @comment wchar.h
481 @comment ISO
482 @deftypefun {wchar_t *} wmemmove (wchar *@var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
483 @code{wmemmove} copies the @var{size} wide characters at @var{wfrom}
484 into the @var{size} wide characters at @var{wto}, even if those two
485 blocks of space overlap.  In the case of overlap, @code{memmove} is
486 careful to copy the original values of the wide characters in the block
487 at @var{wfrom}, including those wide characters which also belong to the
488 block at @var{wto}.
490 The following is a possible implementation of @code{wmemcpy} but there
491 are more optimizations possible.
493 @smallexample
494 wchar_t *
495 wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
496           size_t size)
498   return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
500 @end smallexample
502 The value returned by @code{wmemmove} is the value of @var{wto}.
504 This function is a GNU extension.
505 @end deftypefun
507 @comment string.h
508 @comment SVID
509 @deftypefun {void *} memccpy (void *restrict @var{to}, const void *restrict @var{from}, int @var{c}, size_t @var{size})
510 This function copies no more than @var{size} bytes from @var{from} to
511 @var{to}, stopping if a byte matching @var{c} is found.  The return
512 value is a pointer into @var{to} one byte past where @var{c} was copied,
513 or a null pointer if no byte matching @var{c} appeared in the first
514 @var{size} bytes of @var{from}.
515 @end deftypefun
517 @comment string.h
518 @comment ISO
519 @deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
520 This function copies the value of @var{c} (converted to an
521 @code{unsigned char}) into each of the first @var{size} bytes of the
522 object beginning at @var{block}.  It returns the value of @var{block}.
523 @end deftypefun
525 @comment wchar.h
526 @comment ISO
527 @deftypefun {wchar_t *} wmemset (wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
528 This function copies the value of @var{wc} into each of the first
529 @var{size} wide characters of the object beginning at @var{block}.  It
530 returns the value of @var{block}.
531 @end deftypefun
533 @comment string.h
534 @comment ISO
535 @deftypefun {char *} strcpy (char *restrict @var{to}, const char *restrict @var{from})
536 This copies characters from the string @var{from} (up to and including
537 the terminating null character) into the string @var{to}.  Like
538 @code{memcpy}, this function has undefined results if the strings
539 overlap.  The return value is the value of @var{to}.
540 @end deftypefun
542 @comment wchar.h
543 @comment ISO
544 @deftypefun {wchar_t *} wcscpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
545 This copies wide characters from the string @var{wfrom} (up to and
546 including the terminating null wide character) into the string
547 @var{wto}.  Like @code{wmemcpy}, this function has undefined results if
548 the strings overlap.  The return value is the value of @var{wto}.
549 @end deftypefun
551 @comment string.h
552 @comment ISO
553 @deftypefun {char *} strncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
554 This function is similar to @code{strcpy} but always copies exactly
555 @var{size} characters into @var{to}.
557 If the length of @var{from} is more than @var{size}, then @code{strncpy}
558 copies just the first @var{size} characters.  Note that in this case
559 there is no null terminator written into @var{to}.
561 If the length of @var{from} is less than @var{size}, then @code{strncpy}
562 copies all of @var{from}, followed by enough null characters to add up
563 to @var{size} characters in all.  This behavior is rarely useful, but it
564 is specified by the @w{ISO C} standard.
566 The behavior of @code{strncpy} is undefined if the strings overlap.
568 Using @code{strncpy} as opposed to @code{strcpy} is a way to avoid bugs
569 relating to writing past the end of the allocated space for @var{to}.
570 However, it can also make your program much slower in one common case:
571 copying a string which is probably small into a potentially large buffer.
572 In this case, @var{size} may be large, and when it is, @code{strncpy} will
573 waste a considerable amount of time copying null characters.
574 @end deftypefun
576 @comment wchar.h
577 @comment ISO
578 @deftypefun {wchar_t *} wcsncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
579 This function is similar to @code{wcscpy} but always copies exactly
580 @var{size} wide characters into @var{wto}.
582 If the length of @var{wfrom} is more than @var{size}, then
583 @code{wcsncpy} copies just the first @var{size} wide characters.  Note
584 that in this case there is no null terminator written into @var{wto}.
586 If the length of @var{wfrom} is less than @var{size}, then
587 @code{wcsncpy} copies all of @var{wfrom}, followed by enough null wide
588 characters to add up to @var{size} wide characters in all.  This
589 behavior is rarely useful, but it is specified by the @w{ISO C}
590 standard.
592 The behavior of @code{wcsncpy} is undefined if the strings overlap.
594 Using @code{wcsncpy} as opposed to @code{wcscpy} is a way to avoid bugs
595 relating to writing past the end of the allocated space for @var{wto}.
596 However, it can also make your program much slower in one common case:
597 copying a string which is probably small into a potentially large buffer.
598 In this case, @var{size} may be large, and when it is, @code{wcsncpy} will
599 waste a considerable amount of time copying null wide characters.
600 @end deftypefun
602 @comment string.h
603 @comment SVID
604 @deftypefun {char *} strdup (const char *@var{s})
605 This function copies the null-terminated string @var{s} into a newly
606 allocated string.  The string is allocated using @code{malloc}; see
607 @ref{Unconstrained Allocation}.  If @code{malloc} cannot allocate space
608 for the new string, @code{strdup} returns a null pointer.  Otherwise it
609 returns a pointer to the new string.
610 @end deftypefun
612 @comment wchar.h
613 @comment GNU
614 @deftypefun {wchar_t *} wcsdup (const wchar_t *@var{ws})
615 This function copies the null-terminated wide character string @var{ws}
616 into a newly allocated string.  The string is allocated using
617 @code{malloc}; see @ref{Unconstrained Allocation}.  If @code{malloc}
618 cannot allocate space for the new string, @code{wcsdup} returns a null
619 pointer.  Otherwise it returns a pointer to the new wide character
620 string.
622 This function is a GNU extension.
623 @end deftypefun
625 @comment string.h
626 @comment GNU
627 @deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
628 This function is similar to @code{strdup} but always copies at most
629 @var{size} characters into the newly allocated string.
631 If the length of @var{s} is more than @var{size}, then @code{strndup}
632 copies just the first @var{size} characters and adds a closing null
633 terminator.  Otherwise all characters are copied and the string is
634 terminated.
636 This function is different to @code{strncpy} in that it always
637 terminates the destination string.
639 @code{strndup} is a GNU extension.
640 @end deftypefun
642 @comment string.h
643 @comment Unknown origin
644 @deftypefun {char *} stpcpy (char *restrict @var{to}, const char *restrict @var{from})
645 This function is like @code{strcpy}, except that it returns a pointer to
646 the end of the string @var{to} (that is, the address of the terminating
647 null character @code{to + strlen (from)}) rather than the beginning.
649 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
650 and @samp{bar} to produce @samp{foobar}, which it then prints.
652 @smallexample
653 @include stpcpy.c.texi
654 @end smallexample
656 This function is not part of the ISO or POSIX standards, and is not
657 customary on Unix systems, but we did not invent it either.  Perhaps it
658 comes from MS-DOG.
660 Its behavior is undefined if the strings overlap.  The function is
661 declared in @file{string.h}.
662 @end deftypefun
664 @comment wchar.h
665 @comment GNU
666 @deftypefun {wchar_t *} wcpcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
667 This function is like @code{wcscpy}, except that it returns a pointer to
668 the end of the string @var{wto} (that is, the address of the terminating
669 null character @code{wto + strlen (wfrom)}) rather than the beginning.
671 This function is not part of ISO or POSIX but was found useful while
672 developing @theglibc{} itself.
674 The behavior of @code{wcpcpy} is undefined if the strings overlap.
676 @code{wcpcpy} is a GNU extension and is declared in @file{wchar.h}.
677 @end deftypefun
679 @comment string.h
680 @comment GNU
681 @deftypefun {char *} stpncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
682 This function is similar to @code{stpcpy} but copies always exactly
683 @var{size} characters into @var{to}.
685 If the length of @var{from} is more then @var{size}, then @code{stpncpy}
686 copies just the first @var{size} characters and returns a pointer to the
687 character directly following the one which was copied last.  Note that in
688 this case there is no null terminator written into @var{to}.
690 If the length of @var{from} is less than @var{size}, then @code{stpncpy}
691 copies all of @var{from}, followed by enough null characters to add up
692 to @var{size} characters in all.  This behavior is rarely useful, but it
693 is implemented to be useful in contexts where this behavior of the
694 @code{strncpy} is used.  @code{stpncpy} returns a pointer to the
695 @emph{first} written null character.
697 This function is not part of ISO or POSIX but was found useful while
698 developing @theglibc{} itself.
700 Its behavior is undefined if the strings overlap.  The function is
701 declared in @file{string.h}.
702 @end deftypefun
704 @comment wchar.h
705 @comment GNU
706 @deftypefun {wchar_t *} wcpncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
707 This function is similar to @code{wcpcpy} but copies always exactly
708 @var{wsize} characters into @var{wto}.
710 If the length of @var{wfrom} is more then @var{size}, then
711 @code{wcpncpy} copies just the first @var{size} wide characters and
712 returns a pointer to the wide character directly following the last
713 non-null wide character which was copied last.  Note that in this case
714 there is no null terminator written into @var{wto}.
716 If the length of @var{wfrom} is less than @var{size}, then @code{wcpncpy}
717 copies all of @var{wfrom}, followed by enough null characters to add up
718 to @var{size} characters in all.  This behavior is rarely useful, but it
719 is implemented to be useful in contexts where this behavior of the
720 @code{wcsncpy} is used.  @code{wcpncpy} returns a pointer to the
721 @emph{first} written null character.
723 This function is not part of ISO or POSIX but was found useful while
724 developing @theglibc{} itself.
726 Its behavior is undefined if the strings overlap.
728 @code{wcpncpy} is a GNU extension and is declared in @file{wchar.h}.
729 @end deftypefun
731 @comment string.h
732 @comment GNU
733 @deftypefn {Macro} {char *} strdupa (const char *@var{s})
734 This macro is similar to @code{strdup} but allocates the new string
735 using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
736 Automatic}).  This means of course the returned string has the same
737 limitations as any block of memory allocated using @code{alloca}.
739 For obvious reasons @code{strdupa} is implemented only as a macro;
740 you cannot get the address of this function.  Despite this limitation
741 it is a useful function.  The following code shows a situation where
742 using @code{malloc} would be a lot more expensive.
744 @smallexample
745 @include strdupa.c.texi
746 @end smallexample
748 Please note that calling @code{strtok} using @var{path} directly is
749 invalid.  It is also not allowed to call @code{strdupa} in the argument
750 list of @code{strtok} since @code{strdupa} uses @code{alloca}
751 (@pxref{Variable Size Automatic}) can interfere with the parameter
752 passing.
754 This function is only available if GNU CC is used.
755 @end deftypefn
757 @comment string.h
758 @comment GNU
759 @deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
760 This function is similar to @code{strndup} but like @code{strdupa} it
761 allocates the new string using @code{alloca}
762 @pxref{Variable Size Automatic}.  The same advantages and limitations
763 of @code{strdupa} are valid for @code{strndupa}, too.
765 This function is implemented only as a macro, just like @code{strdupa}.
766 Just as @code{strdupa} this macro also must not be used inside the
767 parameter list in a function call.
769 @code{strndupa} is only available if GNU CC is used.
770 @end deftypefn
772 @comment string.h
773 @comment ISO
774 @deftypefun {char *} strcat (char *restrict @var{to}, const char *restrict @var{from})
775 The @code{strcat} function is similar to @code{strcpy}, except that the
776 characters from @var{from} are concatenated or appended to the end of
777 @var{to}, instead of overwriting it.  That is, the first character from
778 @var{from} overwrites the null character marking the end of @var{to}.
780 An equivalent definition for @code{strcat} would be:
782 @smallexample
783 char *
784 strcat (char *restrict to, const char *restrict from)
786   strcpy (to + strlen (to), from);
787   return to;
789 @end smallexample
791 This function has undefined results if the strings overlap.
792 @end deftypefun
794 @comment wchar.h
795 @comment ISO
796 @deftypefun {wchar_t *} wcscat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
797 The @code{wcscat} function is similar to @code{wcscpy}, except that the
798 characters from @var{wfrom} are concatenated or appended to the end of
799 @var{wto}, instead of overwriting it.  That is, the first character from
800 @var{wfrom} overwrites the null character marking the end of @var{wto}.
802 An equivalent definition for @code{wcscat} would be:
804 @smallexample
805 wchar_t *
806 wcscat (wchar_t *wto, const wchar_t *wfrom)
808   wcscpy (wto + wcslen (wto), wfrom);
809   return wto;
811 @end smallexample
813 This function has undefined results if the strings overlap.
814 @end deftypefun
816 Programmers using the @code{strcat} or @code{wcscat} function (or the
817 following @code{strncat} or @code{wcsncar} functions for that matter)
818 can easily be recognized as lazy and reckless.  In almost all situations
819 the lengths of the participating strings are known (it better should be
820 since how can one otherwise ensure the allocated size of the buffer is
821 sufficient?)  Or at least, one could know them if one keeps track of the
822 results of the various function calls.  But then it is very inefficient
823 to use @code{strcat}/@code{wcscat}.  A lot of time is wasted finding the
824 end of the destination string so that the actual copying can start.
825 This is a common example:
827 @cindex va_copy
828 @smallexample
829 /* @r{This function concatenates arbitrarily many strings.  The last}
830    @r{parameter must be @code{NULL}.}  */
831 char *
832 concat (const char *str, @dots{})
834   va_list ap, ap2;
835   size_t total = 1;
836   const char *s;
837   char *result;
839   va_start (ap, str);
840   va_copy (ap2, ap);
842   /* @r{Determine how much space we need.}  */
843   for (s = str; s != NULL; s = va_arg (ap, const char *))
844     total += strlen (s);
846   va_end (ap);
848   result = (char *) malloc (total);
849   if (result != NULL)
850     @{
851       result[0] = '\0';
853       /* @r{Copy the strings.}  */
854       for (s = str; s != NULL; s = va_arg (ap2, const char *))
855         strcat (result, s);
856     @}
858   va_end (ap2);
860   return result;
862 @end smallexample
864 This looks quite simple, especially the second loop where the strings
865 are actually copied.  But these innocent lines hide a major performance
866 penalty.  Just imagine that ten strings of 100 bytes each have to be
867 concatenated.  For the second string we search the already stored 100
868 bytes for the end of the string so that we can append the next string.
869 For all strings in total the comparisons necessary to find the end of
870 the intermediate results sums up to 5500!  If we combine the copying
871 with the search for the allocation we can write this function more
872 efficient:
874 @smallexample
875 char *
876 concat (const char *str, @dots{})
878   va_list ap;
879   size_t allocated = 100;
880   char *result = (char *) malloc (allocated);
882   if (result != NULL)
883     @{
884       char *newp;
885       char *wp;
886       const char *s;
888       va_start (ap, str);
890       wp = result;
891       for (s = str; s != NULL; s = va_arg (ap, const char *))
892         @{
893           size_t len = strlen (s);
895           /* @r{Resize the allocated memory if necessary.}  */
896           if (wp + len + 1 > result + allocated)
897             @{
898               allocated = (allocated + len) * 2;
899               newp = (char *) realloc (result, allocated);
900               if (newp == NULL)
901                 @{
902                   free (result);
903                   return NULL;
904                 @}
905               wp = newp + (wp - result);
906               result = newp;
907             @}
909           wp = mempcpy (wp, s, len);
910         @}
912       /* @r{Terminate the result string.}  */
913       *wp++ = '\0';
915       /* @r{Resize memory to the optimal size.}  */
916       newp = realloc (result, wp - result);
917       if (newp != NULL)
918         result = newp;
920       va_end (ap);
921     @}
923   return result;
925 @end smallexample
927 With a bit more knowledge about the input strings one could fine-tune
928 the memory allocation.  The difference we are pointing to here is that
929 we don't use @code{strcat} anymore.  We always keep track of the length
930 of the current intermediate result so we can safe us the search for the
931 end of the string and use @code{mempcpy}.  Please note that we also
932 don't use @code{stpcpy} which might seem more natural since we handle
933 with strings.  But this is not necessary since we already know the
934 length of the string and therefore can use the faster memory copying
935 function.  The example would work for wide characters the same way.
937 Whenever a programmer feels the need to use @code{strcat} she or he
938 should think twice and look through the program whether the code cannot
939 be rewritten to take advantage of already calculated results.  Again: it
940 is almost always unnecessary to use @code{strcat}.
942 @comment string.h
943 @comment ISO
944 @deftypefun {char *} strncat (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
945 This function is like @code{strcat} except that not more than @var{size}
946 characters from @var{from} are appended to the end of @var{to}.  A
947 single null character is also always appended to @var{to}, so the total
948 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
949 longer than its initial length.
951 The @code{strncat} function could be implemented like this:
953 @smallexample
954 @group
955 char *
956 strncat (char *to, const char *from, size_t size)
958   to[strlen (to) + size] = '\0';
959   strncpy (to + strlen (to), from, size);
960   return to;
962 @end group
963 @end smallexample
965 The behavior of @code{strncat} is undefined if the strings overlap.
966 @end deftypefun
968 @comment wchar.h
969 @comment ISO
970 @deftypefun {wchar_t *} wcsncat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
971 This function is like @code{wcscat} except that not more than @var{size}
972 characters from @var{from} are appended to the end of @var{to}.  A
973 single null character is also always appended to @var{to}, so the total
974 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
975 longer than its initial length.
977 The @code{wcsncat} function could be implemented like this:
979 @smallexample
980 @group
981 wchar_t *
982 wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom,
983          size_t size)
985   wto[wcslen (to) + size] = L'\0';
986   wcsncpy (wto + wcslen (wto), wfrom, size);
987   return wto;
989 @end group
990 @end smallexample
992 The behavior of @code{wcsncat} is undefined if the strings overlap.
993 @end deftypefun
995 Here is an example showing the use of @code{strncpy} and @code{strncat}
996 (the wide character version is equivalent).  Notice how, in the call to
997 @code{strncat}, the @var{size} parameter is computed to avoid
998 overflowing the character array @code{buffer}.
1000 @smallexample
1001 @include strncat.c.texi
1002 @end smallexample
1004 @noindent
1005 The output produced by this program looks like:
1007 @smallexample
1008 hello
1009 hello, wo
1010 @end smallexample
1012 @comment string.h
1013 @comment BSD
1014 @deftypefun void bcopy (const void *@var{from}, void *@var{to}, size_t @var{size})
1015 This is a partially obsolete alternative for @code{memmove}, derived from
1016 BSD.  Note that it is not quite equivalent to @code{memmove}, because the
1017 arguments are not in the same order and there is no return value.
1018 @end deftypefun
1020 @comment string.h
1021 @comment BSD
1022 @deftypefun void bzero (void *@var{block}, size_t @var{size})
1023 This is a partially obsolete alternative for @code{memset}, derived from
1024 BSD.  Note that it is not as general as @code{memset}, because the only
1025 value it can store is zero.
1026 @end deftypefun
1028 @node String/Array Comparison
1029 @section String/Array Comparison
1030 @cindex comparing strings and arrays
1031 @cindex string comparison functions
1032 @cindex array comparison functions
1033 @cindex predicates on strings
1034 @cindex predicates on arrays
1036 You can use the functions in this section to perform comparisons on the
1037 contents of strings and arrays.  As well as checking for equality, these
1038 functions can also be used as the ordering functions for sorting
1039 operations.  @xref{Searching and Sorting}, for an example of this.
1041 Unlike most comparison operations in C, the string comparison functions
1042 return a nonzero value if the strings are @emph{not} equivalent rather
1043 than if they are.  The sign of the value indicates the relative ordering
1044 of the first characters in the strings that are not equivalent:  a
1045 negative value indicates that the first string is ``less'' than the
1046 second, while a positive value indicates that the first string is
1047 ``greater''.
1049 The most common use of these functions is to check only for equality.
1050 This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
1052 All of these functions are declared in the header file @file{string.h}.
1053 @pindex string.h
1055 @comment string.h
1056 @comment ISO
1057 @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
1058 The function @code{memcmp} compares the @var{size} bytes of memory
1059 beginning at @var{a1} against the @var{size} bytes of memory beginning
1060 at @var{a2}.  The value returned has the same sign as the difference
1061 between the first differing pair of bytes (interpreted as @code{unsigned
1062 char} objects, then promoted to @code{int}).
1064 If the contents of the two blocks are equal, @code{memcmp} returns
1065 @code{0}.
1066 @end deftypefun
1068 @comment wcjar.h
1069 @comment ISO
1070 @deftypefun int wmemcmp (const wchar_t *@var{a1}, const wchar_t *@var{a2}, size_t @var{size})
1071 The function @code{wmemcmp} compares the @var{size} wide characters
1072 beginning at @var{a1} against the @var{size} wide characters beginning
1073 at @var{a2}.  The value returned is smaller than or larger than zero
1074 depending on whether the first differing wide character is @var{a1} is
1075 smaller or larger than the corresponding character in @var{a2}.
1077 If the contents of the two blocks are equal, @code{wmemcmp} returns
1078 @code{0}.
1079 @end deftypefun
1081 On arbitrary arrays, the @code{memcmp} function is mostly useful for
1082 testing equality.  It usually isn't meaningful to do byte-wise ordering
1083 comparisons on arrays of things other than bytes.  For example, a
1084 byte-wise comparison on the bytes that make up floating-point numbers
1085 isn't likely to tell you anything about the relationship between the
1086 values of the floating-point numbers.
1088 @code{wmemcmp} is really only useful to compare arrays of type
1089 @code{wchar_t} since the function looks at @code{sizeof (wchar_t)} bytes
1090 at a time and this number of bytes is system dependent.
1092 You should also be careful about using @code{memcmp} to compare objects
1093 that can contain ``holes'', such as the padding inserted into structure
1094 objects to enforce alignment requirements, extra space at the end of
1095 unions, and extra characters at the ends of strings whose length is less
1096 than their allocated size.  The contents of these ``holes'' are
1097 indeterminate and may cause strange behavior when performing byte-wise
1098 comparisons.  For more predictable results, perform an explicit
1099 component-wise comparison.
1101 For example, given a structure type definition like:
1103 @smallexample
1104 struct foo
1105   @{
1106     unsigned char tag;
1107     union
1108       @{
1109         double f;
1110         long i;
1111         char *p;
1112       @} value;
1113   @};
1114 @end smallexample
1116 @noindent
1117 you are better off writing a specialized comparison function to compare
1118 @code{struct foo} objects instead of comparing them with @code{memcmp}.
1120 @comment string.h
1121 @comment ISO
1122 @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
1123 The @code{strcmp} function compares the string @var{s1} against
1124 @var{s2}, returning a value that has the same sign as the difference
1125 between the first differing pair of characters (interpreted as
1126 @code{unsigned char} objects, then promoted to @code{int}).
1128 If the two strings are equal, @code{strcmp} returns @code{0}.
1130 A consequence of the ordering used by @code{strcmp} is that if @var{s1}
1131 is an initial substring of @var{s2}, then @var{s1} is considered to be
1132 ``less than'' @var{s2}.
1134 @code{strcmp} does not take sorting conventions of the language the
1135 strings are written in into account.  To get that one has to use
1136 @code{strcoll}.
1137 @end deftypefun
1139 @comment wchar.h
1140 @comment ISO
1141 @deftypefun int wcscmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1143 The @code{wcscmp} function compares the wide character string @var{ws1}
1144 against @var{ws2}.  The value returned is smaller than or larger than zero
1145 depending on whether the first differing wide character is @var{ws1} is
1146 smaller or larger than the corresponding character in @var{ws2}.
1148 If the two strings are equal, @code{wcscmp} returns @code{0}.
1150 A consequence of the ordering used by @code{wcscmp} is that if @var{ws1}
1151 is an initial substring of @var{ws2}, then @var{ws1} is considered to be
1152 ``less than'' @var{ws2}.
1154 @code{wcscmp} does not take sorting conventions of the language the
1155 strings are written in into account.  To get that one has to use
1156 @code{wcscoll}.
1157 @end deftypefun
1159 @comment string.h
1160 @comment BSD
1161 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
1162 This function is like @code{strcmp}, except that differences in case are
1163 ignored.  How uppercase and lowercase characters are related is
1164 determined by the currently selected locale.  In the standard @code{"C"}
1165 locale the characters @"A and @"a do not match but in a locale which
1166 regards these characters as parts of the alphabet they do match.
1168 @noindent
1169 @code{strcasecmp} is derived from BSD.
1170 @end deftypefun
1172 @comment wchar.h
1173 @comment GNU
1174 @deftypefun int wcscasecmp (const wchar_t *@var{ws1}, const wchar_T *@var{ws2})
1175 This function is like @code{wcscmp}, except that differences in case are
1176 ignored.  How uppercase and lowercase characters are related is
1177 determined by the currently selected locale.  In the standard @code{"C"}
1178 locale the characters @"A and @"a do not match but in a locale which
1179 regards these characters as parts of the alphabet they do match.
1181 @noindent
1182 @code{wcscasecmp} is a GNU extension.
1183 @end deftypefun
1185 @comment string.h
1186 @comment ISO
1187 @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
1188 This function is the similar to @code{strcmp}, except that no more than
1189 @var{size} characters are compared.  In other words, if the two
1190 strings are the same in their first @var{size} characters, the
1191 return value is zero.
1192 @end deftypefun
1194 @comment wchar.h
1195 @comment ISO
1196 @deftypefun int wcsncmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2}, size_t @var{size})
1197 This function is the similar to @code{wcscmp}, except that no more than
1198 @var{size} wide characters are compared.  In other words, if the two
1199 strings are the same in their first @var{size} wide characters, the
1200 return value is zero.
1201 @end deftypefun
1203 @comment string.h
1204 @comment BSD
1205 @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
1206 This function is like @code{strncmp}, except that differences in case
1207 are ignored.  Like @code{strcasecmp}, it is locale dependent how
1208 uppercase and lowercase characters are related.
1210 @noindent
1211 @code{strncasecmp} is a GNU extension.
1212 @end deftypefun
1214 @comment wchar.h
1215 @comment GNU
1216 @deftypefun int wcsncasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{s2}, size_t @var{n})
1217 This function is like @code{wcsncmp}, except that differences in case
1218 are ignored.  Like @code{wcscasecmp}, it is locale dependent how
1219 uppercase and lowercase characters are related.
1221 @noindent
1222 @code{wcsncasecmp} is a GNU extension.
1223 @end deftypefun
1225 Here are some examples showing the use of @code{strcmp} and
1226 @code{strncmp} (equivalent examples can be constructed for the wide
1227 character functions).  These examples assume the use of the ASCII
1228 character set.  (If some other character set---say, EBCDIC---is used
1229 instead, then the glyphs are associated with different numeric codes,
1230 and the return values and ordering may differ.)
1232 @smallexample
1233 strcmp ("hello", "hello")
1234     @result{} 0    /* @r{These two strings are the same.} */
1235 strcmp ("hello", "Hello")
1236     @result{} 32   /* @r{Comparisons are case-sensitive.} */
1237 strcmp ("hello", "world")
1238     @result{} -15  /* @r{The character @code{'h'} comes before @code{'w'}.} */
1239 strcmp ("hello", "hello, world")
1240     @result{} -44  /* @r{Comparing a null character against a comma.} */
1241 strncmp ("hello", "hello, world", 5)
1242     @result{} 0    /* @r{The initial 5 characters are the same.} */
1243 strncmp ("hello, world", "hello, stupid world!!!", 5)
1244     @result{} 0    /* @r{The initial 5 characters are the same.} */
1245 @end smallexample
1247 @comment string.h
1248 @comment GNU
1249 @deftypefun int strverscmp (const char *@var{s1}, const char *@var{s2})
1250 The @code{strverscmp} function compares the string @var{s1} against
1251 @var{s2}, considering them as holding indices/version numbers.  The
1252 return value follows the same conventions as found in the
1253 @code{strcmp} function.  In fact, if @var{s1} and @var{s2} contain no
1254 digits, @code{strverscmp} behaves like @code{strcmp}.
1256 Basically, we compare strings normally (character by character), until
1257 we find a digit in each string - then we enter a special comparison
1258 mode, where each sequence of digits is taken as a whole.  If we reach the
1259 end of these two parts without noticing a difference, we return to the
1260 standard comparison mode.  There are two types of numeric parts:
1261 "integral" and "fractional" (those  begin with a '0'). The types
1262 of the numeric parts affect the way we sort them:
1264 @itemize @bullet
1265 @item
1266 integral/integral: we compare values as you would expect.
1268 @item
1269 fractional/integral: the fractional part is less than the integral one.
1270 Again, no surprise.
1272 @item
1273 fractional/fractional: the things become a bit more complex.
1274 If the common prefix contains only leading zeroes, the longest part is less
1275 than the other one; else the comparison behaves normally.
1276 @end itemize
1278 @smallexample
1279 strverscmp ("no digit", "no digit")
1280     @result{} 0    /* @r{same behavior as strcmp.} */
1281 strverscmp ("item#99", "item#100")
1282     @result{} <0   /* @r{same prefix, but 99 < 100.} */
1283 strverscmp ("alpha1", "alpha001")
1284     @result{} >0   /* @r{fractional part inferior to integral one.} */
1285 strverscmp ("part1_f012", "part1_f01")
1286     @result{} >0   /* @r{two fractional parts.} */
1287 strverscmp ("foo.009", "foo.0")
1288     @result{} <0   /* @r{idem, but with leading zeroes only.} */
1289 @end smallexample
1291 This function is especially useful when dealing with filename sorting,
1292 because filenames frequently hold indices/version numbers.
1294 @code{strverscmp} is a GNU extension.
1295 @end deftypefun
1297 @comment string.h
1298 @comment BSD
1299 @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
1300 This is an obsolete alias for @code{memcmp}, derived from BSD.
1301 @end deftypefun
1303 @node Collation Functions
1304 @section Collation Functions
1306 @cindex collating strings
1307 @cindex string collation functions
1309 In some locales, the conventions for lexicographic ordering differ from
1310 the strict numeric ordering of character codes.  For example, in Spanish
1311 most glyphs with diacritical marks such as accents are not considered
1312 distinct letters for the purposes of collation.  On the other hand, the
1313 two-character sequence @samp{ll} is treated as a single letter that is
1314 collated immediately after @samp{l}.
1316 You can use the functions @code{strcoll} and @code{strxfrm} (declared in
1317 the headers file @file{string.h}) and @code{wcscoll} and @code{wcsxfrm}
1318 (declared in the headers file @file{wchar}) to compare strings using a
1319 collation ordering appropriate for the current locale.  The locale used
1320 by these functions in particular can be specified by setting the locale
1321 for the @code{LC_COLLATE} category; see @ref{Locales}.
1322 @pindex string.h
1323 @pindex wchar.h
1325 In the standard C locale, the collation sequence for @code{strcoll} is
1326 the same as that for @code{strcmp}.  Similarly, @code{wcscoll} and
1327 @code{wcscmp} are the same in this situation.
1329 Effectively, the way these functions work is by applying a mapping to
1330 transform the characters in a string to a byte sequence that represents
1331 the string's position in the collating sequence of the current locale.
1332 Comparing two such byte sequences in a simple fashion is equivalent to
1333 comparing the strings with the locale's collating sequence.
1335 The functions @code{strcoll} and @code{wcscoll} perform this translation
1336 implicitly, in order to do one comparison.  By contrast, @code{strxfrm}
1337 and @code{wcsxfrm} perform the mapping explicitly.  If you are making
1338 multiple comparisons using the same string or set of strings, it is
1339 likely to be more efficient to use @code{strxfrm} or @code{wcsxfrm} to
1340 transform all the strings just once, and subsequently compare the
1341 transformed strings with @code{strcmp} or @code{wcscmp}.
1343 @comment string.h
1344 @comment ISO
1345 @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
1346 The @code{strcoll} function is similar to @code{strcmp} but uses the
1347 collating sequence of the current locale for collation (the
1348 @code{LC_COLLATE} locale).
1349 @end deftypefun
1351 @comment wchar.h
1352 @comment ISO
1353 @deftypefun int wcscoll (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1354 The @code{wcscoll} function is similar to @code{wcscmp} but uses the
1355 collating sequence of the current locale for collation (the
1356 @code{LC_COLLATE} locale).
1357 @end deftypefun
1359 Here is an example of sorting an array of strings, using @code{strcoll}
1360 to compare them.  The actual sort algorithm is not written here; it
1361 comes from @code{qsort} (@pxref{Array Sort Function}).  The job of the
1362 code shown here is to say how to compare the strings while sorting them.
1363 (Later on in this section, we will show a way to do this more
1364 efficiently using @code{strxfrm}.)
1366 @smallexample
1367 /* @r{This is the comparison function used with @code{qsort}.} */
1370 compare_elements (const void *v1, const void *v2)
1372   char * const *p1 = v1;
1373   char * const *p1 = v2;
1375   return strcoll (*p1, *p2);
1378 /* @r{This is the entry point---the function to sort}
1379    @r{strings using the locale's collating sequence.} */
1381 void
1382 sort_strings (char **array, int nstrings)
1384   /* @r{Sort @code{temp_array} by comparing the strings.} */
1385   qsort (array, nstrings,
1386          sizeof (char *), compare_elements);
1388 @end smallexample
1390 @cindex converting string to collation order
1391 @comment string.h
1392 @comment ISO
1393 @deftypefun size_t strxfrm (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
1394 The function @code{strxfrm} transforms the string @var{from} using the
1395 collation transformation determined by the locale currently selected for
1396 collation, and stores the transformed string in the array @var{to}.  Up
1397 to @var{size} characters (including a terminating null character) are
1398 stored.
1400 The behavior is undefined if the strings @var{to} and @var{from}
1401 overlap; see @ref{Copying and Concatenation}.
1403 The return value is the length of the entire transformed string.  This
1404 value is not affected by the value of @var{size}, but if it is greater
1405 or equal than @var{size}, it means that the transformed string did not
1406 entirely fit in the array @var{to}.  In this case, only as much of the
1407 string as actually fits was stored.  To get the whole transformed
1408 string, call @code{strxfrm} again with a bigger output array.
1410 The transformed string may be longer than the original string, and it
1411 may also be shorter.
1413 If @var{size} is zero, no characters are stored in @var{to}.  In this
1414 case, @code{strxfrm} simply returns the number of characters that would
1415 be the length of the transformed string.  This is useful for determining
1416 what size the allocated array should be.  It does not matter what
1417 @var{to} is if @var{size} is zero; @var{to} may even be a null pointer.
1418 @end deftypefun
1420 @comment wchar.h
1421 @comment ISO
1422 @deftypefun size_t wcsxfrm (wchar_t *restrict @var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
1423 The function @code{wcsxfrm} transforms wide character string @var{wfrom}
1424 using the collation transformation determined by the locale currently
1425 selected for collation, and stores the transformed string in the array
1426 @var{wto}.  Up to @var{size} wide characters (including a terminating null
1427 character) are stored.
1429 The behavior is undefined if the strings @var{wto} and @var{wfrom}
1430 overlap; see @ref{Copying and Concatenation}.
1432 The return value is the length of the entire transformed wide character
1433 string.  This value is not affected by the value of @var{size}, but if
1434 it is greater or equal than @var{size}, it means that the transformed
1435 wide character string did not entirely fit in the array @var{wto}.  In
1436 this case, only as much of the wide character string as actually fits
1437 was stored.  To get the whole transformed wide character string, call
1438 @code{wcsxfrm} again with a bigger output array.
1440 The transformed wide character string may be longer than the original
1441 wide character string, and it may also be shorter.
1443 If @var{size} is zero, no characters are stored in @var{to}.  In this
1444 case, @code{wcsxfrm} simply returns the number of wide characters that
1445 would be the length of the transformed wide character string.  This is
1446 useful for determining what size the allocated array should be (remember
1447 to multiply with @code{sizeof (wchar_t)}).  It does not matter what
1448 @var{wto} is if @var{size} is zero; @var{wto} may even be a null pointer.
1449 @end deftypefun
1451 Here is an example of how you can use @code{strxfrm} when
1452 you plan to do many comparisons.  It does the same thing as the previous
1453 example, but much faster, because it has to transform each string only
1454 once, no matter how many times it is compared with other strings.  Even
1455 the time needed to allocate and free storage is much less than the time
1456 we save, when there are many strings.
1458 @smallexample
1459 struct sorter @{ char *input; char *transformed; @};
1461 /* @r{This is the comparison function used with @code{qsort}}
1462    @r{to sort an array of @code{struct sorter}.} */
1465 compare_elements (const void *v1, const void *v2)
1467   const struct sorter *p1 = v1;
1468   const struct sorter *p2 = v2;
1470   return strcmp (p1->transformed, p2->transformed);
1473 /* @r{This is the entry point---the function to sort}
1474    @r{strings using the locale's collating sequence.} */
1476 void
1477 sort_strings_fast (char **array, int nstrings)
1479   struct sorter temp_array[nstrings];
1480   int i;
1482   /* @r{Set up @code{temp_array}.  Each element contains}
1483      @r{one input string and its transformed string.} */
1484   for (i = 0; i < nstrings; i++)
1485     @{
1486       size_t length = strlen (array[i]) * 2;
1487       char *transformed;
1488       size_t transformed_length;
1490       temp_array[i].input = array[i];
1492       /* @r{First try a buffer perhaps big enough.}  */
1493       transformed = (char *) xmalloc (length);
1495       /* @r{Transform @code{array[i]}.}  */
1496       transformed_length = strxfrm (transformed, array[i], length);
1498       /* @r{If the buffer was not large enough, resize it}
1499          @r{and try again.}  */
1500       if (transformed_length >= length)
1501         @{
1502           /* @r{Allocate the needed space. +1 for terminating}
1503              @r{@code{NUL} character.}  */
1504           transformed = (char *) xrealloc (transformed,
1505                                            transformed_length + 1);
1507           /* @r{The return value is not interesting because we know}
1508              @r{how long the transformed string is.}  */
1509           (void) strxfrm (transformed, array[i],
1510                           transformed_length + 1);
1511         @}
1513       temp_array[i].transformed = transformed;
1514     @}
1516   /* @r{Sort @code{temp_array} by comparing transformed strings.} */
1517   qsort (temp_array, sizeof (struct sorter),
1518          nstrings, compare_elements);
1520   /* @r{Put the elements back in the permanent array}
1521      @r{in their sorted order.} */
1522   for (i = 0; i < nstrings; i++)
1523     array[i] = temp_array[i].input;
1525   /* @r{Free the strings we allocated.} */
1526   for (i = 0; i < nstrings; i++)
1527     free (temp_array[i].transformed);
1529 @end smallexample
1531 The interesting part of this code for the wide character version would
1532 look like this:
1534 @smallexample
1535 void
1536 sort_strings_fast (wchar_t **array, int nstrings)
1538   @dots{}
1539       /* @r{Transform @code{array[i]}.}  */
1540       transformed_length = wcsxfrm (transformed, array[i], length);
1542       /* @r{If the buffer was not large enough, resize it}
1543          @r{and try again.}  */
1544       if (transformed_length >= length)
1545         @{
1546           /* @r{Allocate the needed space. +1 for terminating}
1547              @r{@code{NUL} character.}  */
1548           transformed = (wchar_t *) xrealloc (transformed,
1549                                               (transformed_length + 1)
1550                                               * sizeof (wchar_t));
1552           /* @r{The return value is not interesting because we know}
1553              @r{how long the transformed string is.}  */
1554           (void) wcsxfrm (transformed, array[i],
1555                           transformed_length + 1);
1556         @}
1557   @dots{}
1558 @end smallexample
1560 @noindent
1561 Note the additional multiplication with @code{sizeof (wchar_t)} in the
1562 @code{realloc} call.
1564 @strong{Compatibility Note:} The string collation functions are a new
1565 feature of @w{ISO C90}.  Older C dialects have no equivalent feature.
1566 The wide character versions were introduced in @w{Amendment 1} to @w{ISO
1567 C90}.
1569 @node Search Functions
1570 @section Search Functions
1572 This section describes library functions which perform various kinds
1573 of searching operations on strings and arrays.  These functions are
1574 declared in the header file @file{string.h}.
1575 @pindex string.h
1576 @cindex search functions (for strings)
1577 @cindex string search functions
1579 @comment string.h
1580 @comment ISO
1581 @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
1582 This function finds the first occurrence of the byte @var{c} (converted
1583 to an @code{unsigned char}) in the initial @var{size} bytes of the
1584 object beginning at @var{block}.  The return value is a pointer to the
1585 located byte, or a null pointer if no match was found.
1586 @end deftypefun
1588 @comment wchar.h
1589 @comment ISO
1590 @deftypefun {wchar_t *} wmemchr (const wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
1591 This function finds the first occurrence of the wide character @var{wc}
1592 in the initial @var{size} wide characters of the object beginning at
1593 @var{block}.  The return value is a pointer to the located wide
1594 character, or a null pointer if no match was found.
1595 @end deftypefun
1597 @comment string.h
1598 @comment GNU
1599 @deftypefun {void *} rawmemchr (const void *@var{block}, int @var{c})
1600 Often the @code{memchr} function is used with the knowledge that the
1601 byte @var{c} is available in the memory block specified by the
1602 parameters.  But this means that the @var{size} parameter is not really
1603 needed and that the tests performed with it at runtime (to check whether
1604 the end of the block is reached) are not needed.
1606 The @code{rawmemchr} function exists for just this situation which is
1607 surprisingly frequent.  The interface is similar to @code{memchr} except
1608 that the @var{size} parameter is missing.  The function will look beyond
1609 the end of the block pointed to by @var{block} in case the programmer
1610 made an error in assuming that the byte @var{c} is present in the block.
1611 In this case the result is unspecified.  Otherwise the return value is a
1612 pointer to the located byte.
1614 This function is of special interest when looking for the end of a
1615 string.  Since all strings are terminated by a null byte a call like
1617 @smallexample
1618    rawmemchr (str, '\0')
1619 @end smallexample
1621 @noindent
1622 will never go beyond the end of the string.
1624 This function is a GNU extension.
1625 @end deftypefun
1627 @comment string.h
1628 @comment GNU
1629 @deftypefun {void *} memrchr (const void *@var{block}, int @var{c}, size_t @var{size})
1630 The function @code{memrchr} is like @code{memchr}, except that it searches
1631 backwards from the end of the block defined by @var{block} and @var{size}
1632 (instead of forwards from the front).
1634 This function is a GNU extension.
1635 @end deftypefun
1637 @comment string.h
1638 @comment ISO
1639 @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
1640 The @code{strchr} function finds the first occurrence of the character
1641 @var{c} (converted to a @code{char}) in the null-terminated string
1642 beginning at @var{string}.  The return value is a pointer to the located
1643 character, or a null pointer if no match was found.
1645 For example,
1646 @smallexample
1647 strchr ("hello, world", 'l')
1648     @result{} "llo, world"
1649 strchr ("hello, world", '?')
1650     @result{} NULL
1651 @end smallexample
1653 The terminating null character is considered to be part of the string,
1654 so you can use this function get a pointer to the end of a string by
1655 specifying a null character as the value of the @var{c} argument.
1657 When @code{strchr} returns a null pointer, it does not let you know
1658 the position of the terminating null character it has found.  If you
1659 need that information, it is better (but less portable) to use
1660 @code{strchrnul} than to search for it a second time.
1661 @end deftypefun
1663 @comment wchar.h
1664 @comment ISO
1665 @deftypefun {wchar_t *} wcschr (const wchar_t *@var{wstring}, int @var{wc})
1666 The @code{wcschr} function finds the first occurrence of the wide
1667 character @var{wc} in the null-terminated wide character string
1668 beginning at @var{wstring}.  The return value is a pointer to the
1669 located wide character, or a null pointer if no match was found.
1671 The terminating null character is considered to be part of the wide
1672 character string, so you can use this function get a pointer to the end
1673 of a wide character string by specifying a null wude character as the
1674 value of the @var{wc} argument.  It would be better (but less portable)
1675 to use @code{wcschrnul} in this case, though.
1676 @end deftypefun
1678 @comment string.h
1679 @comment GNU
1680 @deftypefun {char *} strchrnul (const char *@var{string}, int @var{c})
1681 @code{strchrnul} is the same as @code{strchr} except that if it does
1682 not find the character, it returns a pointer to string's terminating
1683 null character rather than a null pointer.
1685 This function is a GNU extension.
1686 @end deftypefun
1688 @comment wchar.h
1689 @comment GNU
1690 @deftypefun {wchar_t *} wcschrnul (const wchar_t *@var{wstring}, wchar_t @var{wc})
1691 @code{wcschrnul} is the same as @code{wcschr} except that if it does not
1692 find the wide character, it returns a pointer to wide character string's
1693 terminating null wide character rather than a null pointer.
1695 This function is a GNU extension.
1696 @end deftypefun
1698 One useful, but unusual, use of the @code{strchr}
1699 function is when one wants to have a pointer pointing to the NUL byte
1700 terminating a string.  This is often written in this way:
1702 @smallexample
1703   s += strlen (s);
1704 @end smallexample
1706 @noindent
1707 This is almost optimal but the addition operation duplicated a bit of
1708 the work already done in the @code{strlen} function.  A better solution
1709 is this:
1711 @smallexample
1712   s = strchr (s, '\0');
1713 @end smallexample
1715 There is no restriction on the second parameter of @code{strchr} so it
1716 could very well also be the NUL character.  Those readers thinking very
1717 hard about this might now point out that the @code{strchr} function is
1718 more expensive than the @code{strlen} function since we have two abort
1719 criteria.  This is right.  But in @theglibc{} the implementation of
1720 @code{strchr} is optimized in a special way so that @code{strchr}
1721 actually is faster.
1723 @comment string.h
1724 @comment ISO
1725 @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
1726 The function @code{strrchr} is like @code{strchr}, except that it searches
1727 backwards from the end of the string @var{string} (instead of forwards
1728 from the front).
1730 For example,
1731 @smallexample
1732 strrchr ("hello, world", 'l')
1733     @result{} "ld"
1734 @end smallexample
1735 @end deftypefun
1737 @comment wchar.h
1738 @comment ISO
1739 @deftypefun {wchar_t *} wcsrchr (const wchar_t *@var{wstring}, wchar_t @var{c})
1740 The function @code{wcsrchr} is like @code{wcschr}, except that it searches
1741 backwards from the end of the string @var{wstring} (instead of forwards
1742 from the front).
1743 @end deftypefun
1745 @comment string.h
1746 @comment ISO
1747 @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
1748 This is like @code{strchr}, except that it searches @var{haystack} for a
1749 substring @var{needle} rather than just a single character.  It
1750 returns a pointer into the string @var{haystack} that is the first
1751 character of the substring, or a null pointer if no match was found.  If
1752 @var{needle} is an empty string, the function returns @var{haystack}.
1754 For example,
1755 @smallexample
1756 strstr ("hello, world", "l")
1757     @result{} "llo, world"
1758 strstr ("hello, world", "wo")
1759     @result{} "world"
1760 @end smallexample
1761 @end deftypefun
1763 @comment wchar.h
1764 @comment ISO
1765 @deftypefun {wchar_t *} wcsstr (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
1766 This is like @code{wcschr}, except that it searches @var{haystack} for a
1767 substring @var{needle} rather than just a single wide character.  It
1768 returns a pointer into the string @var{haystack} that is the first wide
1769 character of the substring, or a null pointer if no match was found.  If
1770 @var{needle} is an empty string, the function returns @var{haystack}.
1771 @end deftypefun
1773 @comment wchar.h
1774 @comment XPG
1775 @deftypefun {wchar_t *} wcswcs (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
1776 @code{wcswcs} is an deprecated alias for @code{wcsstr}.  This is the
1777 name originally used in the X/Open Portability Guide before the
1778 @w{Amendment 1} to @w{ISO C90} was published.
1779 @end deftypefun
1782 @comment string.h
1783 @comment GNU
1784 @deftypefun {char *} strcasestr (const char *@var{haystack}, const char *@var{needle})
1785 This is like @code{strstr}, except that it ignores case in searching for
1786 the substring.   Like @code{strcasecmp}, it is locale dependent how
1787 uppercase and lowercase characters are related.
1790 For example,
1791 @smallexample
1792 strcasestr ("hello, world", "L")
1793     @result{} "llo, world"
1794 strcasestr ("hello, World", "wo")
1795     @result{} "World"
1796 @end smallexample
1797 @end deftypefun
1800 @comment string.h
1801 @comment GNU
1802 @deftypefun {void *} memmem (const void *@var{haystack}, size_t @var{haystack-len},@*const void *@var{needle}, size_t @var{needle-len})
1803 This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
1804 arrays rather than null-terminated strings.  @var{needle-len} is the
1805 length of @var{needle} and @var{haystack-len} is the length of
1806 @var{haystack}.@refill
1808 This function is a GNU extension.
1809 @end deftypefun
1811 @comment string.h
1812 @comment ISO
1813 @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
1814 The @code{strspn} (``string span'') function returns the length of the
1815 initial substring of @var{string} that consists entirely of characters that
1816 are members of the set specified by the string @var{skipset}.  The order
1817 of the characters in @var{skipset} is not important.
1819 For example,
1820 @smallexample
1821 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
1822     @result{} 5
1823 @end smallexample
1825 Note that ``character'' is here used in the sense of byte.  In a string
1826 using a multibyte character encoding (abstract) character consisting of
1827 more than one byte are not treated as an entity.  Each byte is treated
1828 separately.  The function is not locale-dependent.
1829 @end deftypefun
1831 @comment wchar.h
1832 @comment ISO
1833 @deftypefun size_t wcsspn (const wchar_t *@var{wstring}, const wchar_t *@var{skipset})
1834 The @code{wcsspn} (``wide character string span'') function returns the
1835 length of the initial substring of @var{wstring} that consists entirely
1836 of wide characters that are members of the set specified by the string
1837 @var{skipset}.  The order of the wide characters in @var{skipset} is not
1838 important.
1839 @end deftypefun
1841 @comment string.h
1842 @comment ISO
1843 @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
1844 The @code{strcspn} (``string complement span'') function returns the length
1845 of the initial substring of @var{string} that consists entirely of characters
1846 that are @emph{not} members of the set specified by the string @var{stopset}.
1847 (In other words, it returns the offset of the first character in @var{string}
1848 that is a member of the set @var{stopset}.)
1850 For example,
1851 @smallexample
1852 strcspn ("hello, world", " \t\n,.;!?")
1853     @result{} 5
1854 @end smallexample
1856 Note that ``character'' is here used in the sense of byte.  In a string
1857 using a multibyte character encoding (abstract) character consisting of
1858 more than one byte are not treated as an entity.  Each byte is treated
1859 separately.  The function is not locale-dependent.
1860 @end deftypefun
1862 @comment wchar.h
1863 @comment ISO
1864 @deftypefun size_t wcscspn (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
1865 The @code{wcscspn} (``wide character string complement span'') function
1866 returns the length of the initial substring of @var{wstring} that
1867 consists entirely of wide characters that are @emph{not} members of the
1868 set specified by the string @var{stopset}.  (In other words, it returns
1869 the offset of the first character in @var{string} that is a member of
1870 the set @var{stopset}.)
1871 @end deftypefun
1873 @comment string.h
1874 @comment ISO
1875 @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
1876 The @code{strpbrk} (``string pointer break'') function is related to
1877 @code{strcspn}, except that it returns a pointer to the first character
1878 in @var{string} that is a member of the set @var{stopset} instead of the
1879 length of the initial substring.  It returns a null pointer if no such
1880 character from @var{stopset} is found.
1882 @c @group  Invalid outside the example.
1883 For example,
1885 @smallexample
1886 strpbrk ("hello, world", " \t\n,.;!?")
1887     @result{} ", world"
1888 @end smallexample
1889 @c @end group
1891 Note that ``character'' is here used in the sense of byte.  In a string
1892 using a multibyte character encoding (abstract) character consisting of
1893 more than one byte are not treated as an entity.  Each byte is treated
1894 separately.  The function is not locale-dependent.
1895 @end deftypefun
1897 @comment wchar.h
1898 @comment ISO
1899 @deftypefun {wchar_t *} wcspbrk (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
1900 The @code{wcspbrk} (``wide character string pointer break'') function is
1901 related to @code{wcscspn}, except that it returns a pointer to the first
1902 wide character in @var{wstring} that is a member of the set
1903 @var{stopset} instead of the length of the initial substring.  It
1904 returns a null pointer if no such character from @var{stopset} is found.
1905 @end deftypefun
1908 @subsection Compatibility String Search Functions
1910 @comment string.h
1911 @comment BSD
1912 @deftypefun {char *} index (const char *@var{string}, int @var{c})
1913 @code{index} is another name for @code{strchr}; they are exactly the same.
1914 New code should always use @code{strchr} since this name is defined in
1915 @w{ISO C} while @code{index} is a BSD invention which never was available
1916 on @w{System V} derived systems.
1917 @end deftypefun
1919 @comment string.h
1920 @comment BSD
1921 @deftypefun {char *} rindex (const char *@var{string}, int @var{c})
1922 @code{rindex} is another name for @code{strrchr}; they are exactly the same.
1923 New code should always use @code{strrchr} since this name is defined in
1924 @w{ISO C} while @code{rindex} is a BSD invention which never was available
1925 on @w{System V} derived systems.
1926 @end deftypefun
1928 @node Finding Tokens in a String
1929 @section Finding Tokens in a String
1931 @cindex tokenizing strings
1932 @cindex breaking a string into tokens
1933 @cindex parsing tokens from a string
1934 It's fairly common for programs to have a need to do some simple kinds
1935 of lexical analysis and parsing, such as splitting a command string up
1936 into tokens.  You can do this with the @code{strtok} function, declared
1937 in the header file @file{string.h}.
1938 @pindex string.h
1940 @comment string.h
1941 @comment ISO
1942 @deftypefun {char *} strtok (char *restrict @var{newstring}, const char *restrict @var{delimiters})
1943 A string can be split into tokens by making a series of calls to the
1944 function @code{strtok}.
1946 The string to be split up is passed as the @var{newstring} argument on
1947 the first call only.  The @code{strtok} function uses this to set up
1948 some internal state information.  Subsequent calls to get additional
1949 tokens from the same string are indicated by passing a null pointer as
1950 the @var{newstring} argument.  Calling @code{strtok} with another
1951 non-null @var{newstring} argument reinitializes the state information.
1952 It is guaranteed that no other library function ever calls @code{strtok}
1953 behind your back (which would mess up this internal state information).
1955 The @var{delimiters} argument is a string that specifies a set of delimiters
1956 that may surround the token being extracted.  All the initial characters
1957 that are members of this set are discarded.  The first character that is
1958 @emph{not} a member of this set of delimiters marks the beginning of the
1959 next token.  The end of the token is found by looking for the next
1960 character that is a member of the delimiter set.  This character in the
1961 original string @var{newstring} is overwritten by a null character, and the
1962 pointer to the beginning of the token in @var{newstring} is returned.
1964 On the next call to @code{strtok}, the searching begins at the next
1965 character beyond the one that marked the end of the previous token.
1966 Note that the set of delimiters @var{delimiters} do not have to be the
1967 same on every call in a series of calls to @code{strtok}.
1969 If the end of the string @var{newstring} is reached, or if the remainder of
1970 string consists only of delimiter characters, @code{strtok} returns
1971 a null pointer.
1973 Note that ``character'' is here used in the sense of byte.  In a string
1974 using a multibyte character encoding (abstract) character consisting of
1975 more than one byte are not treated as an entity.  Each byte is treated
1976 separately.  The function is not locale-dependent.
1977 @end deftypefun
1979 @comment wchar.h
1980 @comment ISO
1981 @deftypefun {wchar_t *} wcstok (wchar_t *@var{newstring}, const char *@var{delimiters})
1982 A string can be split into tokens by making a series of calls to the
1983 function @code{wcstok}.
1985 The string to be split up is passed as the @var{newstring} argument on
1986 the first call only.  The @code{wcstok} function uses this to set up
1987 some internal state information.  Subsequent calls to get additional
1988 tokens from the same wide character string are indicated by passing a
1989 null pointer as the @var{newstring} argument.  Calling @code{wcstok}
1990 with another non-null @var{newstring} argument reinitializes the state
1991 information.  It is guaranteed that no other library function ever calls
1992 @code{wcstok} behind your back (which would mess up this internal state
1993 information).
1995 The @var{delimiters} argument is a wide character string that specifies
1996 a set of delimiters that may surround the token being extracted.  All
1997 the initial wide characters that are members of this set are discarded.
1998 The first wide character that is @emph{not} a member of this set of
1999 delimiters marks the beginning of the next token.  The end of the token
2000 is found by looking for the next wide character that is a member of the
2001 delimiter set.  This wide character in the original wide character
2002 string @var{newstring} is overwritten by a null wide character, and the
2003 pointer to the beginning of the token in @var{newstring} is returned.
2005 On the next call to @code{wcstok}, the searching begins at the next
2006 wide character beyond the one that marked the end of the previous token.
2007 Note that the set of delimiters @var{delimiters} do not have to be the
2008 same on every call in a series of calls to @code{wcstok}.
2010 If the end of the wide character string @var{newstring} is reached, or
2011 if the remainder of string consists only of delimiter wide characters,
2012 @code{wcstok} returns a null pointer.
2014 Note that ``character'' is here used in the sense of byte.  In a string
2015 using a multibyte character encoding (abstract) character consisting of
2016 more than one byte are not treated as an entity.  Each byte is treated
2017 separately.  The function is not locale-dependent.
2018 @end deftypefun
2020 @strong{Warning:} Since @code{strtok} and @code{wcstok} alter the string
2021 they is parsing, you should always copy the string to a temporary buffer
2022 before parsing it with @code{strtok}/@code{wcstok} (@pxref{Copying and
2023 Concatenation}).  If you allow @code{strtok} or @code{wcstok} to modify
2024 a string that came from another part of your program, you are asking for
2025 trouble; that string might be used for other purposes after
2026 @code{strtok} or @code{wcstok} has modified it, and it would not have
2027 the expected value.
2029 The string that you are operating on might even be a constant.  Then
2030 when @code{strtok} or @code{wcstok} tries to modify it, your program
2031 will get a fatal signal for writing in read-only memory.  @xref{Program
2032 Error Signals}.  Even if the operation of @code{strtok} or @code{wcstok}
2033 would not require a modification of the string (e.g., if there is
2034 exactly one token) the string can (and in the @glibcadj{} case will) be
2035 modified.
2037 This is a special case of a general principle: if a part of a program
2038 does not have as its purpose the modification of a certain data
2039 structure, then it is error-prone to modify the data structure
2040 temporarily.
2042 The functions @code{strtok} and @code{wcstok} are not reentrant.
2043 @xref{Nonreentrancy}, for a discussion of where and why reentrancy is
2044 important.
2046 Here is a simple example showing the use of @code{strtok}.
2048 @comment Yes, this example has been tested.
2049 @smallexample
2050 #include <string.h>
2051 #include <stddef.h>
2053 @dots{}
2055 const char string[] = "words separated by spaces -- and, punctuation!";
2056 const char delimiters[] = " .,;:!-";
2057 char *token, *cp;
2059 @dots{}
2061 cp = strdupa (string);                /* Make writable copy.  */
2062 token = strtok (cp, delimiters);      /* token => "words" */
2063 token = strtok (NULL, delimiters);    /* token => "separated" */
2064 token = strtok (NULL, delimiters);    /* token => "by" */
2065 token = strtok (NULL, delimiters);    /* token => "spaces" */
2066 token = strtok (NULL, delimiters);    /* token => "and" */
2067 token = strtok (NULL, delimiters);    /* token => "punctuation" */
2068 token = strtok (NULL, delimiters);    /* token => NULL */
2069 @end smallexample
2071 @Theglibc{} contains two more functions for tokenizing a string
2072 which overcome the limitation of non-reentrancy.  They are only
2073 available for multibyte character strings.
2075 @comment string.h
2076 @comment POSIX
2077 @deftypefun {char *} strtok_r (char *@var{newstring}, const char *@var{delimiters}, char **@var{save_ptr})
2078 Just like @code{strtok}, this function splits the string into several
2079 tokens which can be accessed by successive calls to @code{strtok_r}.
2080 The difference is that the information about the next token is stored in
2081 the space pointed to by the third argument, @var{save_ptr}, which is a
2082 pointer to a string pointer.  Calling @code{strtok_r} with a null
2083 pointer for @var{newstring} and leaving @var{save_ptr} between the calls
2084 unchanged does the job without hindering reentrancy.
2086 This function is defined in POSIX.1 and can be found on many systems
2087 which support multi-threading.
2088 @end deftypefun
2090 @comment string.h
2091 @comment BSD
2092 @deftypefun {char *} strsep (char **@var{string_ptr}, const char *@var{delimiter})
2093 This function has a similar functionality as @code{strtok_r} with the
2094 @var{newstring} argument replaced by the @var{save_ptr} argument.  The
2095 initialization of the moving pointer has to be done by the user.
2096 Successive calls to @code{strsep} move the pointer along the tokens
2097 separated by @var{delimiter}, returning the address of the next token
2098 and updating @var{string_ptr} to point to the beginning of the next
2099 token.
2101 One difference between @code{strsep} and @code{strtok_r} is that if the
2102 input string contains more than one character from @var{delimiter} in a
2103 row @code{strsep} returns an empty string for each pair of characters
2104 from @var{delimiter}.  This means that a program normally should test
2105 for @code{strsep} returning an empty string before processing it.
2107 This function was introduced in 4.3BSD and therefore is widely available.
2108 @end deftypefun
2110 Here is how the above example looks like when @code{strsep} is used.
2112 @comment Yes, this example has been tested.
2113 @smallexample
2114 #include <string.h>
2115 #include <stddef.h>
2117 @dots{}
2119 const char string[] = "words separated by spaces -- and, punctuation!";
2120 const char delimiters[] = " .,;:!-";
2121 char *running;
2122 char *token;
2124 @dots{}
2126 running = strdupa (string);
2127 token = strsep (&running, delimiters);    /* token => "words" */
2128 token = strsep (&running, delimiters);    /* token => "separated" */
2129 token = strsep (&running, delimiters);    /* token => "by" */
2130 token = strsep (&running, delimiters);    /* token => "spaces" */
2131 token = strsep (&running, delimiters);    /* token => "" */
2132 token = strsep (&running, delimiters);    /* token => "" */
2133 token = strsep (&running, delimiters);    /* token => "" */
2134 token = strsep (&running, delimiters);    /* token => "and" */
2135 token = strsep (&running, delimiters);    /* token => "" */
2136 token = strsep (&running, delimiters);    /* token => "punctuation" */
2137 token = strsep (&running, delimiters);    /* token => "" */
2138 token = strsep (&running, delimiters);    /* token => NULL */
2139 @end smallexample
2141 @comment string.h
2142 @comment GNU
2143 @deftypefun {char *} basename (const char *@var{filename})
2144 The GNU version of the @code{basename} function returns the last
2145 component of the path in @var{filename}.  This function is the preferred
2146 usage, since it does not modify the argument, @var{filename}, and
2147 respects trailing slashes.  The prototype for @code{basename} can be
2148 found in @file{string.h}.  Note, this function is overriden by the XPG
2149 version, if @file{libgen.h} is included.
2151 Example of using GNU @code{basename}:
2153 @smallexample
2154 #include <string.h>
2157 main (int argc, char *argv[])
2159   char *prog = basename (argv[0]);
2161   if (argc < 2)
2162     @{
2163       fprintf (stderr, "Usage %s <arg>\n", prog);
2164       exit (1);
2165     @}
2167   @dots{}
2169 @end smallexample
2171 @strong{Portability Note:} This function may produce different results
2172 on different systems.
2174 @end deftypefun
2176 @comment libgen.h
2177 @comment XPG
2178 @deftypefun {char *} basename (char *@var{path})
2179 This is the standard XPG defined @code{basename}. It is similar in
2180 spirit to the GNU version, but may modify the @var{path} by removing
2181 trailing '/' characters.  If the @var{path} is made up entirely of '/'
2182 characters, then "/" will be returned.  Also, if @var{path} is
2183 @code{NULL} or an empty string, then "." is returned.  The prototype for
2184 the XPG version can be found in @file{libgen.h}.
2186 Example of using XPG @code{basename}:
2188 @smallexample
2189 #include <libgen.h>
2192 main (int argc, char *argv[])
2194   char *prog;
2195   char *path = strdupa (argv[0]);
2197   prog = basename (path);
2199   if (argc < 2)
2200     @{
2201       fprintf (stderr, "Usage %s <arg>\n", prog);
2202       exit (1);
2203     @}
2205   @dots{}
2208 @end smallexample
2209 @end deftypefun
2211 @comment libgen.h
2212 @comment XPG
2213 @deftypefun {char *} dirname (char *@var{path})
2214 The @code{dirname} function is the compliment to the XPG version of
2215 @code{basename}.  It returns the parent directory of the file specified
2216 by @var{path}.  If @var{path} is @code{NULL}, an empty string, or
2217 contains no '/' characters, then "." is returned.  The prototype for this
2218 function can be found in @file{libgen.h}.
2219 @end deftypefun
2221 @node strfry
2222 @section strfry
2224 The function below addresses the perennial programming quandary: ``How do
2225 I take good data in string form and painlessly turn it into garbage?''
2226 This is actually a fairly simple task for C programmers who do not use
2227 @theglibc{} string functions, but for programs based on @theglibc{},
2228 the @code{strfry} function is the preferred method for
2229 destroying string data.
2231 The prototype for this function is in @file{string.h}.
2233 @comment string.h
2234 @comment GNU
2235 @deftypefun {char *} strfry (char *@var{string})
2237 @code{strfry} creates a pseudorandom anagram of a string, replacing the
2238 input with the anagram in place.  For each position in the string,
2239 @code{strfry} swaps it with a position in the string selected at random
2240 (from a uniform distribution).  The two positions may be the same.
2242 The return value of @code{strfry} is always @var{string}.
2244 @strong{Portability Note:}  This function is unique to @theglibc{}.
2246 @end deftypefun
2249 @node Trivial Encryption
2250 @section Trivial Encryption
2251 @cindex encryption
2254 The @code{memfrob} function converts an array of data to something
2255 unrecognizable and back again.  It is not encryption in its usual sense
2256 since it is easy for someone to convert the encrypted data back to clear
2257 text.  The transformation is analogous to Usenet's ``Rot13'' encryption
2258 method for obscuring offensive jokes from sensitive eyes and such.
2259 Unlike Rot13, @code{memfrob} works on arbitrary binary data, not just
2260 text.
2261 @cindex Rot13
2263 For true encryption, @xref{Cryptographic Functions}.
2265 This function is declared in @file{string.h}.
2266 @pindex string.h
2268 @comment string.h
2269 @comment GNU
2270 @deftypefun {void *} memfrob (void *@var{mem}, size_t @var{length})
2272 @code{memfrob} transforms (frobnicates) each byte of the data structure
2273 at @var{mem}, which is @var{length} bytes long, by bitwise exclusive
2274 oring it with binary 00101010.  It does the transformation in place and
2275 its return value is always @var{mem}.
2277 Note that @code{memfrob} a second time on the same data structure
2278 returns it to its original state.
2280 This is a good function for hiding information from someone who doesn't
2281 want to see it or doesn't want to see it very much.  To really prevent
2282 people from retrieving the information, use stronger encryption such as
2283 that described in @xref{Cryptographic Functions}.
2285 @strong{Portability Note:}  This function is unique to @theglibc{}.
2287 @end deftypefun
2289 @node Encode Binary Data
2290 @section Encode Binary Data
2292 To store or transfer binary data in environments which only support text
2293 one has to encode the binary data by mapping the input bytes to
2294 characters in the range allowed for storing or transfering.  SVID
2295 systems (and nowadays XPG compliant systems) provide minimal support for
2296 this task.
2298 @comment stdlib.h
2299 @comment XPG
2300 @deftypefun {char *} l64a (long int @var{n})
2301 This function encodes a 32-bit input value using characters from the
2302 basic character set.  It returns a pointer to a 7 character buffer which
2303 contains an encoded version of @var{n}.  To encode a series of bytes the
2304 user must copy the returned string to a destination buffer.  It returns
2305 the empty string if @var{n} is zero, which is somewhat bizarre but
2306 mandated by the standard.@*
2307 @strong{Warning:} Since a static buffer is used this function should not
2308 be used in multi-threaded programs.  There is no thread-safe alternative
2309 to this function in the C library.@*
2310 @strong{Compatibility Note:} The XPG standard states that the return
2311 value of @code{l64a} is undefined if @var{n} is negative.  In the GNU
2312 implementation, @code{l64a} treats its argument as unsigned, so it will
2313 return a sensible encoding for any nonzero @var{n}; however, portable
2314 programs should not rely on this.
2316 To encode a large buffer @code{l64a} must be called in a loop, once for
2317 each 32-bit word of the buffer.  For example, one could do something
2318 like this:
2320 @smallexample
2321 char *
2322 encode (const void *buf, size_t len)
2324   /* @r{We know in advance how long the buffer has to be.} */
2325   unsigned char *in = (unsigned char *) buf;
2326   char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
2327   char *cp = out, *p;
2329   /* @r{Encode the length.} */
2330   /* @r{Using `htonl' is necessary so that the data can be}
2331      @r{decoded even on machines with different byte order.}
2332      @r{`l64a' can return a string shorter than 6 bytes, so }
2333      @r{we pad it with encoding of 0 (}'.'@r{) at the end by }
2334      @r{hand.} */
2336   p = stpcpy (cp, l64a (htonl (len)));
2337   cp = mempcpy (p, "......", 6 - (p - cp));
2339   while (len > 3)
2340     @{
2341       unsigned long int n = *in++;
2342       n = (n << 8) | *in++;
2343       n = (n << 8) | *in++;
2344       n = (n << 8) | *in++;
2345       len -= 4;
2346       p = stpcpy (cp, l64a (htonl (n)));
2347       cp = mempcpy (p, "......", 6 - (p - cp));
2348     @}
2349   if (len > 0)
2350     @{
2351       unsigned long int n = *in++;
2352       if (--len > 0)
2353         @{
2354           n = (n << 8) | *in++;
2355           if (--len > 0)
2356             n = (n << 8) | *in;
2357         @}
2358       cp = stpcpy (cp, l64a (htonl (n)));
2359     @}
2360   *cp = '\0';
2361   return out;
2363 @end smallexample
2365 It is strange that the library does not provide the complete
2366 functionality needed but so be it.
2368 @end deftypefun
2370 To decode data produced with @code{l64a} the following function should be
2371 used.
2373 @comment stdlib.h
2374 @comment XPG
2375 @deftypefun {long int} a64l (const char *@var{string})
2376 The parameter @var{string} should contain a string which was produced by
2377 a call to @code{l64a}.  The function processes at least 6 characters of
2378 this string, and decodes the characters it finds according to the table
2379 below.  It stops decoding when it finds a character not in the table,
2380 rather like @code{atoi}; if you have a buffer which has been broken into
2381 lines, you must be careful to skip over the end-of-line characters.
2383 The decoded number is returned as a @code{long int} value.
2384 @end deftypefun
2386 The @code{l64a} and @code{a64l} functions use a base 64 encoding, in
2387 which each character of an encoded string represents six bits of an
2388 input word.  These symbols are used for the base 64 digits:
2390 @multitable {xxxxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx}
2391 @item              @tab 0 @tab 1 @tab 2 @tab 3 @tab 4 @tab 5 @tab 6 @tab 7
2392 @item       0      @tab @code{.} @tab @code{/} @tab @code{0} @tab @code{1}
2393                    @tab @code{2} @tab @code{3} @tab @code{4} @tab @code{5}
2394 @item       8      @tab @code{6} @tab @code{7} @tab @code{8} @tab @code{9}
2395                    @tab @code{A} @tab @code{B} @tab @code{C} @tab @code{D}
2396 @item       16     @tab @code{E} @tab @code{F} @tab @code{G} @tab @code{H}
2397                    @tab @code{I} @tab @code{J} @tab @code{K} @tab @code{L}
2398 @item       24     @tab @code{M} @tab @code{N} @tab @code{O} @tab @code{P}
2399                    @tab @code{Q} @tab @code{R} @tab @code{S} @tab @code{T}
2400 @item       32     @tab @code{U} @tab @code{V} @tab @code{W} @tab @code{X}
2401                    @tab @code{Y} @tab @code{Z} @tab @code{a} @tab @code{b}
2402 @item       40     @tab @code{c} @tab @code{d} @tab @code{e} @tab @code{f}
2403                    @tab @code{g} @tab @code{h} @tab @code{i} @tab @code{j}
2404 @item       48     @tab @code{k} @tab @code{l} @tab @code{m} @tab @code{n}
2405                    @tab @code{o} @tab @code{p} @tab @code{q} @tab @code{r}
2406 @item       56     @tab @code{s} @tab @code{t} @tab @code{u} @tab @code{v}
2407                    @tab @code{w} @tab @code{x} @tab @code{y} @tab @code{z}
2408 @end multitable
2410 This encoding scheme is not standard.  There are some other encoding
2411 methods which are much more widely used (UU encoding, MIME encoding).
2412 Generally, it is better to use one of these encodings.
2414 @node Argz and Envz Vectors
2415 @section Argz and Envz Vectors
2417 @cindex argz vectors (string vectors)
2418 @cindex string vectors, null-character separated
2419 @cindex argument vectors, null-character separated
2420 @dfn{argz vectors} are vectors of strings in a contiguous block of
2421 memory, each element separated from its neighbors by null-characters
2422 (@code{'\0'}).
2424 @cindex envz vectors (environment vectors)
2425 @cindex environment vectors, null-character separated
2426 @dfn{Envz vectors} are an extension of argz vectors where each element is a
2427 name-value pair, separated by a @code{'='} character (as in a Unix
2428 environment).
2430 @menu
2431 * Argz Functions::              Operations on argz vectors.
2432 * Envz Functions::              Additional operations on environment vectors.
2433 @end menu
2435 @node Argz Functions, Envz Functions, , Argz and Envz Vectors
2436 @subsection Argz Functions
2438 Each argz vector is represented by a pointer to the first element, of
2439 type @code{char *}, and a size, of type @code{size_t}, both of which can
2440 be initialized to @code{0} to represent an empty argz vector.  All argz
2441 functions accept either a pointer and a size argument, or pointers to
2442 them, if they will be modified.
2444 The argz functions use @code{malloc}/@code{realloc} to allocate/grow
2445 argz vectors, and so any argz vector creating using these functions may
2446 be freed by using @code{free}; conversely, any argz function that may
2447 grow a string expects that string to have been allocated using
2448 @code{malloc} (those argz functions that only examine their arguments or
2449 modify them in place will work on any sort of memory).
2450 @xref{Unconstrained Allocation}.
2452 All argz functions that do memory allocation have a return type of
2453 @code{error_t}, and return @code{0} for success, and @code{ENOMEM} if an
2454 allocation error occurs.
2456 @pindex argz.h
2457 These functions are declared in the standard include file @file{argz.h}.
2459 @comment argz.h
2460 @comment GNU
2461 @deftypefun {error_t} argz_create (char *const @var{argv}[], char **@var{argz}, size_t *@var{argz_len})
2462 The @code{argz_create} function converts the Unix-style argument vector
2463 @var{argv} (a vector of pointers to normal C strings, terminated by
2464 @code{(char *)0}; @pxref{Program Arguments}) into an argz vector with
2465 the same elements, which is returned in @var{argz} and @var{argz_len}.
2466 @end deftypefun
2468 @comment argz.h
2469 @comment GNU
2470 @deftypefun {error_t} argz_create_sep (const char *@var{string}, int @var{sep}, char **@var{argz}, size_t *@var{argz_len})
2471 The @code{argz_create_sep} function converts the null-terminated string
2472 @var{string} into an argz vector (returned in @var{argz} and
2473 @var{argz_len}) by splitting it into elements at every occurrence of the
2474 character @var{sep}.
2475 @end deftypefun
2477 @comment argz.h
2478 @comment GNU
2479 @deftypefun {size_t} argz_count (const char *@var{argz}, size_t @var{arg_len})
2480 Returns the number of elements in the argz vector @var{argz} and
2481 @var{argz_len}.
2482 @end deftypefun
2484 @comment argz.h
2485 @comment GNU
2486 @deftypefun {void} argz_extract (char *@var{argz}, size_t @var{argz_len}, char **@var{argv})
2487 The @code{argz_extract} function converts the argz vector @var{argz} and
2488 @var{argz_len} into a Unix-style argument vector stored in @var{argv},
2489 by putting pointers to every element in @var{argz} into successive
2490 positions in @var{argv}, followed by a terminator of @code{0}.
2491 @var{Argv} must be pre-allocated with enough space to hold all the
2492 elements in @var{argz} plus the terminating @code{(char *)0}
2493 (@code{(argz_count (@var{argz}, @var{argz_len}) + 1) * sizeof (char *)}
2494 bytes should be enough).  Note that the string pointers stored into
2495 @var{argv} point into @var{argz}---they are not copies---and so
2496 @var{argz} must be copied if it will be changed while @var{argv} is
2497 still active.  This function is useful for passing the elements in
2498 @var{argz} to an exec function (@pxref{Executing a File}).
2499 @end deftypefun
2501 @comment argz.h
2502 @comment GNU
2503 @deftypefun {void} argz_stringify (char *@var{argz}, size_t @var{len}, int @var{sep})
2504 The @code{argz_stringify} converts @var{argz} into a normal string with
2505 the elements separated by the character @var{sep}, by replacing each
2506 @code{'\0'} inside @var{argz} (except the last one, which terminates the
2507 string) with @var{sep}.  This is handy for printing @var{argz} in a
2508 readable manner.
2509 @end deftypefun
2511 @comment argz.h
2512 @comment GNU
2513 @deftypefun {error_t} argz_add (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str})
2514 The @code{argz_add} function adds the string @var{str} to the end of the
2515 argz vector @code{*@var{argz}}, and updates @code{*@var{argz}} and
2516 @code{*@var{argz_len}} accordingly.
2517 @end deftypefun
2519 @comment argz.h
2520 @comment GNU
2521 @deftypefun {error_t} argz_add_sep (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str}, int @var{delim})
2522 The @code{argz_add_sep} function is similar to @code{argz_add}, but
2523 @var{str} is split into separate elements in the result at occurrences of
2524 the character @var{delim}.  This is useful, for instance, for
2525 adding the components of a Unix search path to an argz vector, by using
2526 a value of @code{':'} for @var{delim}.
2527 @end deftypefun
2529 @comment argz.h
2530 @comment GNU
2531 @deftypefun {error_t} argz_append (char **@var{argz}, size_t *@var{argz_len}, const char *@var{buf}, size_t @var{buf_len})
2532 The @code{argz_append} function appends @var{buf_len} bytes starting at
2533 @var{buf} to the argz vector @code{*@var{argz}}, reallocating
2534 @code{*@var{argz}} to accommodate it, and adding @var{buf_len} to
2535 @code{*@var{argz_len}}.
2536 @end deftypefun
2538 @comment argz.h
2539 @comment GNU
2540 @deftypefun {void} argz_delete (char **@var{argz}, size_t *@var{argz_len}, char *@var{entry})
2541 If @var{entry} points to the beginning of one of the elements in the
2542 argz vector @code{*@var{argz}}, the @code{argz_delete} function will
2543 remove this entry and reallocate @code{*@var{argz}}, modifying
2544 @code{*@var{argz}} and @code{*@var{argz_len}} accordingly.  Note that as
2545 destructive argz functions usually reallocate their argz argument,
2546 pointers into argz vectors such as @var{entry} will then become invalid.
2547 @end deftypefun
2549 @comment argz.h
2550 @comment GNU
2551 @deftypefun {error_t} argz_insert (char **@var{argz}, size_t *@var{argz_len}, char *@var{before}, const char *@var{entry})
2552 The @code{argz_insert} function inserts the string @var{entry} into the
2553 argz vector @code{*@var{argz}} at a point just before the existing
2554 element pointed to by @var{before}, reallocating @code{*@var{argz}} and
2555 updating @code{*@var{argz}} and @code{*@var{argz_len}}.  If @var{before}
2556 is @code{0}, @var{entry} is added to the end instead (as if by
2557 @code{argz_add}).  Since the first element is in fact the same as
2558 @code{*@var{argz}}, passing in @code{*@var{argz}} as the value of
2559 @var{before} will result in @var{entry} being inserted at the beginning.
2560 @end deftypefun
2562 @comment argz.h
2563 @comment GNU
2564 @deftypefun {char *} argz_next (char *@var{argz}, size_t @var{argz_len}, const char *@var{entry})
2565 The @code{argz_next} function provides a convenient way of iterating
2566 over the elements in the argz vector @var{argz}.  It returns a pointer
2567 to the next element in @var{argz} after the element @var{entry}, or
2568 @code{0} if there are no elements following @var{entry}.  If @var{entry}
2569 is @code{0}, the first element of @var{argz} is returned.
2571 This behavior suggests two styles of iteration:
2573 @smallexample
2574     char *entry = 0;
2575     while ((entry = argz_next (@var{argz}, @var{argz_len}, entry)))
2576       @var{action};
2577 @end smallexample
2579 (the double parentheses are necessary to make some C compilers shut up
2580 about what they consider a questionable @code{while}-test) and:
2582 @smallexample
2583     char *entry;
2584     for (entry = @var{argz};
2585          entry;
2586          entry = argz_next (@var{argz}, @var{argz_len}, entry))
2587       @var{action};
2588 @end smallexample
2590 Note that the latter depends on @var{argz} having a value of @code{0} if
2591 it is empty (rather than a pointer to an empty block of memory); this
2592 invariant is maintained for argz vectors created by the functions here.
2593 @end deftypefun
2595 @comment argz.h
2596 @comment GNU
2597 @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}})
2598 Replace any occurrences of the string @var{str} in @var{argz} with
2599 @var{with}, reallocating @var{argz} as necessary.  If
2600 @var{replace_count} is non-zero, @code{*@var{replace_count}} will be
2601 incremented by number of replacements performed.
2602 @end deftypefun
2604 @node Envz Functions, , Argz Functions, Argz and Envz Vectors
2605 @subsection Envz Functions
2607 Envz vectors are just argz vectors with additional constraints on the form
2608 of each element; as such, argz functions can also be used on them, where it
2609 makes sense.
2611 Each element in an envz vector is a name-value pair, separated by a @code{'='}
2612 character; if multiple @code{'='} characters are present in an element, those
2613 after the first are considered part of the value, and treated like all other
2614 non-@code{'\0'} characters.
2616 If @emph{no} @code{'='} characters are present in an element, that element is
2617 considered the name of a ``null'' entry, as distinct from an entry with an
2618 empty value: @code{envz_get} will return @code{0} if given the name of null
2619 entry, whereas an entry with an empty value would result in a value of
2620 @code{""}; @code{envz_entry} will still find such entries, however.  Null
2621 entries can be removed with @code{envz_strip} function.
2623 As with argz functions, envz functions that may allocate memory (and thus
2624 fail) have a return type of @code{error_t}, and return either @code{0} or
2625 @code{ENOMEM}.
2627 @pindex envz.h
2628 These functions are declared in the standard include file @file{envz.h}.
2630 @comment envz.h
2631 @comment GNU
2632 @deftypefun {char *} envz_entry (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
2633 The @code{envz_entry} function finds the entry in @var{envz} with the name
2634 @var{name}, and returns a pointer to the whole entry---that is, the argz
2635 element which begins with @var{name} followed by a @code{'='} character.  If
2636 there is no entry with that name, @code{0} is returned.
2637 @end deftypefun
2639 @comment envz.h
2640 @comment GNU
2641 @deftypefun {char *} envz_get (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
2642 The @code{envz_get} function finds the entry in @var{envz} with the name
2643 @var{name} (like @code{envz_entry}), and returns a pointer to the value
2644 portion of that entry (following the @code{'='}).  If there is no entry with
2645 that name (or only a null entry), @code{0} is returned.
2646 @end deftypefun
2648 @comment envz.h
2649 @comment GNU
2650 @deftypefun {error_t} envz_add (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name}, const char *@var{value})
2651 The @code{envz_add} function adds an entry to @code{*@var{envz}}
2652 (updating @code{*@var{envz}} and @code{*@var{envz_len}}) with the name
2653 @var{name}, and value @var{value}.  If an entry with the same name
2654 already exists in @var{envz}, it is removed first.  If @var{value} is
2655 @code{0}, then the new entry will the special null type of entry
2656 (mentioned above).
2657 @end deftypefun
2659 @comment envz.h
2660 @comment GNU
2661 @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})
2662 The @code{envz_merge} function adds each entry in @var{envz2} to @var{envz},
2663 as if with @code{envz_add}, updating @code{*@var{envz}} and
2664 @code{*@var{envz_len}}.  If @var{override} is true, then values in @var{envz2}
2665 will supersede those with the same name in @var{envz}, otherwise not.
2667 Null entries are treated just like other entries in this respect, so a null
2668 entry in @var{envz} can prevent an entry of the same name in @var{envz2} from
2669 being added to @var{envz}, if @var{override} is false.
2670 @end deftypefun
2672 @comment envz.h
2673 @comment GNU
2674 @deftypefun {void} envz_strip (char **@var{envz}, size_t *@var{envz_len})
2675 The @code{envz_strip} function removes any null entries from @var{envz},
2676 updating @code{*@var{envz}} and @code{*@var{envz_len}}.
2677 @end deftypefun