2.9
[glibc/nacl-glibc.git] / manual / string.texi
blob2fe60395ebd2607b6bed0cb130ac51fc34e92412
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.  The GNU C library 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}) < n ? strlen (@var{s}) : @var{maxlen})} but it
307 is more efficient and works even if the string @var{s} is not
308 null-terminated.
310 @smallexample
311 char string[32] = "hello, world";
312 strnlen (string, 32)
313     @result{} 12
314 strnlen (string, 5)
315     @result{} 5
316 @end smallexample
318 This function is a GNU extension and is declared in @file{string.h}.
319 @end deftypefun
321 @comment wchar.h
322 @comment GNU
323 @deftypefun size_t wcsnlen (const wchar_t *@var{ws}, size_t @var{maxlen})
324 @code{wcsnlen} is the wide character equivalent to @code{strnlen}.  The
325 @var{maxlen} parameter specifies the maximum number of wide characters.
327 This function is a GNU extension and is declared in @file{wchar.h}.
328 @end deftypefun
330 @node Copying and Concatenation
331 @section Copying and Concatenation
333 You can use the functions described in this section to copy the contents
334 of strings and arrays, or to append the contents of one string to
335 another.  The @samp{str} and @samp{mem} functions are declared in the
336 header file @file{string.h} while the @samp{wstr} and @samp{wmem}
337 functions are declared in the file @file{wchar.h}.
338 @pindex string.h
339 @pindex wchar.h
340 @cindex copying strings and arrays
341 @cindex string copy functions
342 @cindex array copy functions
343 @cindex concatenating strings
344 @cindex string concatenation functions
346 A helpful way to remember the ordering of the arguments to the functions
347 in this section is that it corresponds to an assignment expression, with
348 the destination array specified to the left of the source array.  All
349 of these functions return the address of the destination array.
351 Most of these functions do not work properly if the source and
352 destination arrays overlap.  For example, if the beginning of the
353 destination array overlaps the end of the source array, the original
354 contents of that part of the source array may get overwritten before it
355 is copied.  Even worse, in the case of the string functions, the null
356 character marking the end of the string may be lost, and the copy
357 function might get stuck in a loop trashing all the memory allocated to
358 your program.
360 All functions that have problems copying between overlapping arrays are
361 explicitly identified in this manual.  In addition to functions in this
362 section, there are a few others like @code{sprintf} (@pxref{Formatted
363 Output Functions}) and @code{scanf} (@pxref{Formatted Input
364 Functions}).
366 @comment string.h
367 @comment ISO
368 @deftypefun {void *} memcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
369 The @code{memcpy} function copies @var{size} bytes from the object
370 beginning at @var{from} into the object beginning at @var{to}.  The
371 behavior of this function is undefined if the two arrays @var{to} and
372 @var{from} overlap; use @code{memmove} instead if overlapping is possible.
374 The value returned by @code{memcpy} is the value of @var{to}.
376 Here is an example of how you might use @code{memcpy} to copy the
377 contents of an array:
379 @smallexample
380 struct foo *oldarray, *newarray;
381 int arraysize;
382 @dots{}
383 memcpy (new, old, arraysize * sizeof (struct foo));
384 @end smallexample
385 @end deftypefun
387 @comment wchar.h
388 @comment ISO
389 @deftypefun {wchar_t *} wmemcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
390 The @code{wmemcpy} function copies @var{size} wide characters from the object
391 beginning at @var{wfrom} into the object beginning at @var{wto}.  The
392 behavior of this function is undefined if the two arrays @var{wto} and
393 @var{wfrom} overlap; use @code{wmemmove} instead if overlapping is possible.
395 The following is a possible implementation of @code{wmemcpy} but there
396 are more optimizations possible.
398 @smallexample
399 wchar_t *
400 wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
401          size_t size)
403   return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));
405 @end smallexample
407 The value returned by @code{wmemcpy} is the value of @var{wto}.
409 This function was introduced in @w{Amendment 1} to @w{ISO C90}.
410 @end deftypefun
412 @comment string.h
413 @comment GNU
414 @deftypefun {void *} mempcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
415 The @code{mempcpy} function is nearly identical to the @code{memcpy}
416 function.  It copies @var{size} bytes from the object beginning at
417 @code{from} into the object pointed to by @var{to}.  But instead of
418 returning the value of @var{to} it returns a pointer to the byte
419 following the last written byte in the object beginning at @var{to}.
420 I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
422 This function is useful in situations where a number of objects shall be
423 copied to consecutive memory positions.
425 @smallexample
426 void *
427 combine (void *o1, size_t s1, void *o2, size_t s2)
429   void *result = malloc (s1 + s2);
430   if (result != NULL)
431     mempcpy (mempcpy (result, o1, s1), o2, s2);
432   return result;
434 @end smallexample
436 This function is a GNU extension.
437 @end deftypefun
439 @comment wchar.h
440 @comment GNU
441 @deftypefun {wchar_t *} wmempcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
442 The @code{wmempcpy} function is nearly identical to the @code{wmemcpy}
443 function.  It copies @var{size} wide characters from the object
444 beginning at @code{wfrom} into the object pointed to by @var{wto}.  But
445 instead of returning the value of @var{wto} it returns a pointer to the
446 wide character following the last written wide character in the object
447 beginning at @var{wto}.  I.e., the value is @code{@var{wto} + @var{size}}.
449 This function is useful in situations where a number of objects shall be
450 copied to consecutive memory positions.
452 The following is a possible implementation of @code{wmemcpy} but there
453 are more optimizations possible.
455 @smallexample
456 wchar_t *
457 wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
458           size_t size)
460   return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
462 @end smallexample
464 This function is a GNU extension.
465 @end deftypefun
467 @comment string.h
468 @comment ISO
469 @deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
470 @code{memmove} copies the @var{size} bytes at @var{from} into the
471 @var{size} bytes at @var{to}, even if those two blocks of space
472 overlap.  In the case of overlap, @code{memmove} is careful to copy the
473 original values of the bytes in the block at @var{from}, including those
474 bytes which also belong to the block at @var{to}.
476 The value returned by @code{memmove} is the value of @var{to}.
477 @end deftypefun
479 @comment wchar.h
480 @comment ISO
481 @deftypefun {wchar_t *} wmemmove (wchar *@var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
482 @code{wmemmove} copies the @var{size} wide characters at @var{wfrom}
483 into the @var{size} wide characters at @var{wto}, even if those two
484 blocks of space overlap.  In the case of overlap, @code{memmove} is
485 careful to copy the original values of the wide characters in the block
486 at @var{wfrom}, including those wide characters which also belong to the
487 block at @var{wto}.
489 The following is a possible implementation of @code{wmemcpy} but there
490 are more optimizations possible.
492 @smallexample
493 wchar_t *
494 wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
495           size_t size)
497   return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
499 @end smallexample
501 The value returned by @code{wmemmove} is the value of @var{wto}.
503 This function is a GNU extension.
504 @end deftypefun
506 @comment string.h
507 @comment SVID
508 @deftypefun {void *} memccpy (void *restrict @var{to}, const void *restrict @var{from}, int @var{c}, size_t @var{size})
509 This function copies no more than @var{size} bytes from @var{from} to
510 @var{to}, stopping if a byte matching @var{c} is found.  The return
511 value is a pointer into @var{to} one byte past where @var{c} was copied,
512 or a null pointer if no byte matching @var{c} appeared in the first
513 @var{size} bytes of @var{from}.
514 @end deftypefun
516 @comment string.h
517 @comment ISO
518 @deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
519 This function copies the value of @var{c} (converted to an
520 @code{unsigned char}) into each of the first @var{size} bytes of the
521 object beginning at @var{block}.  It returns the value of @var{block}.
522 @end deftypefun
524 @comment wchar.h
525 @comment ISO
526 @deftypefun {wchar_t *} wmemset (wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
527 This function copies the value of @var{wc} into each of the first
528 @var{size} wide characters of the object beginning at @var{block}.  It
529 returns the value of @var{block}.
530 @end deftypefun
532 @comment string.h
533 @comment ISO
534 @deftypefun {char *} strcpy (char *restrict @var{to}, const char *restrict @var{from})
535 This copies characters from the string @var{from} (up to and including
536 the terminating null character) into the string @var{to}.  Like
537 @code{memcpy}, this function has undefined results if the strings
538 overlap.  The return value is the value of @var{to}.
539 @end deftypefun
541 @comment wchar.h
542 @comment ISO
543 @deftypefun {wchar_t *} wcscpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
544 This copies wide characters from the string @var{wfrom} (up to and
545 including the terminating null wide character) into the string
546 @var{wto}.  Like @code{wmemcpy}, this function has undefined results if
547 the strings overlap.  The return value is the value of @var{wto}.
548 @end deftypefun
550 @comment string.h
551 @comment ISO
552 @deftypefun {char *} strncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
553 This function is similar to @code{strcpy} but always copies exactly
554 @var{size} characters into @var{to}.
556 If the length of @var{from} is more than @var{size}, then @code{strncpy}
557 copies just the first @var{size} characters.  Note that in this case
558 there is no null terminator written into @var{to}.
560 If the length of @var{from} is less than @var{size}, then @code{strncpy}
561 copies all of @var{from}, followed by enough null characters to add up
562 to @var{size} characters in all.  This behavior is rarely useful, but it
563 is specified by the @w{ISO C} standard.
565 The behavior of @code{strncpy} is undefined if the strings overlap.
567 Using @code{strncpy} as opposed to @code{strcpy} is a way to avoid bugs
568 relating to writing past the end of the allocated space for @var{to}.
569 However, it can also make your program much slower in one common case:
570 copying a string which is probably small into a potentially large buffer.
571 In this case, @var{size} may be large, and when it is, @code{strncpy} will
572 waste a considerable amount of time copying null characters.
573 @end deftypefun
575 @comment wchar.h
576 @comment ISO
577 @deftypefun {wchar_t *} wcsncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
578 This function is similar to @code{wcscpy} but always copies exactly
579 @var{size} wide characters into @var{wto}.
581 If the length of @var{wfrom} is more than @var{size}, then
582 @code{wcsncpy} copies just the first @var{size} wide characters.  Note
583 that in this case there is no null terminator written into @var{wto}.
585 If the length of @var{wfrom} is less than @var{size}, then
586 @code{wcsncpy} copies all of @var{wfrom}, followed by enough null wide
587 characters to add up to @var{size} wide characters in all.  This
588 behavior is rarely useful, but it is specified by the @w{ISO C}
589 standard.
591 The behavior of @code{wcsncpy} is undefined if the strings overlap.
593 Using @code{wcsncpy} as opposed to @code{wcscpy} is a way to avoid bugs
594 relating to writing past the end of the allocated space for @var{wto}.
595 However, it can also make your program much slower in one common case:
596 copying a string which is probably small into a potentially large buffer.
597 In this case, @var{size} may be large, and when it is, @code{wcsncpy} will
598 waste a considerable amount of time copying null wide characters.
599 @end deftypefun
601 @comment string.h
602 @comment SVID
603 @deftypefun {char *} strdup (const char *@var{s})
604 This function copies the null-terminated string @var{s} into a newly
605 allocated string.  The string is allocated using @code{malloc}; see
606 @ref{Unconstrained Allocation}.  If @code{malloc} cannot allocate space
607 for the new string, @code{strdup} returns a null pointer.  Otherwise it
608 returns a pointer to the new string.
609 @end deftypefun
611 @comment wchar.h
612 @comment GNU
613 @deftypefun {wchar_t *} wcsdup (const wchar_t *@var{ws})
614 This function copies the null-terminated wide character string @var{ws}
615 into a newly allocated string.  The string is allocated using
616 @code{malloc}; see @ref{Unconstrained Allocation}.  If @code{malloc}
617 cannot allocate space for the new string, @code{wcsdup} returns a null
618 pointer.  Otherwise it returns a pointer to the new wide character
619 string.
621 This function is a GNU extension.
622 @end deftypefun
624 @comment string.h
625 @comment GNU
626 @deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
627 This function is similar to @code{strdup} but always copies at most
628 @var{size} characters into the newly allocated string.
630 If the length of @var{s} is more than @var{size}, then @code{strndup}
631 copies just the first @var{size} characters and adds a closing null
632 terminator.  Otherwise all characters are copied and the string is
633 terminated.
635 This function is different to @code{strncpy} in that it always
636 terminates the destination string.
638 @code{strndup} is a GNU extension.
639 @end deftypefun
641 @comment string.h
642 @comment Unknown origin
643 @deftypefun {char *} stpcpy (char *restrict @var{to}, const char *restrict @var{from})
644 This function is like @code{strcpy}, except that it returns a pointer to
645 the end of the string @var{to} (that is, the address of the terminating
646 null character @code{to + strlen (from)}) rather than the beginning.
648 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
649 and @samp{bar} to produce @samp{foobar}, which it then prints.
651 @smallexample
652 @include stpcpy.c.texi
653 @end smallexample
655 This function is not part of the ISO or POSIX standards, and is not
656 customary on Unix systems, but we did not invent it either.  Perhaps it
657 comes from MS-DOG.
659 Its behavior is undefined if the strings overlap.  The function is
660 declared in @file{string.h}.
661 @end deftypefun
663 @comment wchar.h
664 @comment GNU
665 @deftypefun {wchar_t *} wcpcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
666 This function is like @code{wcscpy}, except that it returns a pointer to
667 the end of the string @var{wto} (that is, the address of the terminating
668 null character @code{wto + strlen (wfrom)}) rather than the beginning.
670 This function is not part of ISO or POSIX but was found useful while
671 developing the GNU C Library itself.
673 The behavior of @code{wcpcpy} is undefined if the strings overlap.
675 @code{wcpcpy} is a GNU extension and is declared in @file{wchar.h}.
676 @end deftypefun
678 @comment string.h
679 @comment GNU
680 @deftypefun {char *} stpncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
681 This function is similar to @code{stpcpy} but copies always exactly
682 @var{size} characters into @var{to}.
684 If the length of @var{from} is more then @var{size}, then @code{stpncpy}
685 copies just the first @var{size} characters and returns a pointer to the
686 character directly following the one which was copied last.  Note that in
687 this case there is no null terminator written into @var{to}.
689 If the length of @var{from} is less than @var{size}, then @code{stpncpy}
690 copies all of @var{from}, followed by enough null characters to add up
691 to @var{size} characters in all.  This behavior is rarely useful, but it
692 is implemented to be useful in contexts where this behavior of the
693 @code{strncpy} is used.  @code{stpncpy} returns a pointer to the
694 @emph{first} written null character.
696 This function is not part of ISO or POSIX but was found useful while
697 developing the GNU C Library itself.
699 Its behavior is undefined if the strings overlap.  The function is
700 declared in @file{string.h}.
701 @end deftypefun
703 @comment wchar.h
704 @comment GNU
705 @deftypefun {wchar_t *} wcpncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
706 This function is similar to @code{wcpcpy} but copies always exactly
707 @var{wsize} characters into @var{wto}.
709 If the length of @var{wfrom} is more then @var{size}, then
710 @code{wcpncpy} copies just the first @var{size} wide characters and
711 returns a pointer to the wide character directly following the last
712 non-null wide character which was copied last.  Note that in this case
713 there is no null terminator written into @var{wto}.
715 If the length of @var{wfrom} is less than @var{size}, then @code{wcpncpy}
716 copies all of @var{wfrom}, followed by enough null characters to add up
717 to @var{size} characters in all.  This behavior is rarely useful, but it
718 is implemented to be useful in contexts where this behavior of the
719 @code{wcsncpy} is used.  @code{wcpncpy} returns a pointer to the
720 @emph{first} written null character.
722 This function is not part of ISO or POSIX but was found useful while
723 developing the GNU C Library itself.
725 Its behavior is undefined if the strings overlap.
727 @code{wcpncpy} is a GNU extension and is declared in @file{wchar.h}.
728 @end deftypefun
730 @comment string.h
731 @comment GNU
732 @deftypefn {Macro} {char *} strdupa (const char *@var{s})
733 This macro is similar to @code{strdup} but allocates the new string
734 using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
735 Automatic}).  This means of course the returned string has the same
736 limitations as any block of memory allocated using @code{alloca}.
738 For obvious reasons @code{strdupa} is implemented only as a macro;
739 you cannot get the address of this function.  Despite this limitation
740 it is a useful function.  The following code shows a situation where
741 using @code{malloc} would be a lot more expensive.
743 @smallexample
744 @include strdupa.c.texi
745 @end smallexample
747 Please note that calling @code{strtok} using @var{path} directly is
748 invalid.  It is also not allowed to call @code{strdupa} in the argument
749 list of @code{strtok} since @code{strdupa} uses @code{alloca}
750 (@pxref{Variable Size Automatic}) can interfere with the parameter
751 passing.
753 This function is only available if GNU CC is used.
754 @end deftypefn
756 @comment string.h
757 @comment GNU
758 @deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
759 This function is similar to @code{strndup} but like @code{strdupa} it
760 allocates the new string using @code{alloca}
761 @pxref{Variable Size Automatic}.  The same advantages and limitations
762 of @code{strdupa} are valid for @code{strndupa}, too.
764 This function is implemented only as a macro, just like @code{strdupa}.
765 Just as @code{strdupa} this macro also must not be used inside the
766 parameter list in a function call.
768 @code{strndupa} is only available if GNU CC is used.
769 @end deftypefn
771 @comment string.h
772 @comment ISO
773 @deftypefun {char *} strcat (char *restrict @var{to}, const char *restrict @var{from})
774 The @code{strcat} function is similar to @code{strcpy}, except that the
775 characters from @var{from} are concatenated or appended to the end of
776 @var{to}, instead of overwriting it.  That is, the first character from
777 @var{from} overwrites the null character marking the end of @var{to}.
779 An equivalent definition for @code{strcat} would be:
781 @smallexample
782 char *
783 strcat (char *restrict to, const char *restrict from)
785   strcpy (to + strlen (to), from);
786   return to;
788 @end smallexample
790 This function has undefined results if the strings overlap.
791 @end deftypefun
793 @comment wchar.h
794 @comment ISO
795 @deftypefun {wchar_t *} wcscat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
796 The @code{wcscat} function is similar to @code{wcscpy}, except that the
797 characters from @var{wfrom} are concatenated or appended to the end of
798 @var{wto}, instead of overwriting it.  That is, the first character from
799 @var{wfrom} overwrites the null character marking the end of @var{wto}.
801 An equivalent definition for @code{wcscat} would be:
803 @smallexample
804 wchar_t *
805 wcscat (wchar_t *wto, const wchar_t *wfrom)
807   wcscpy (wto + wcslen (wto), wfrom);
808   return wto;
810 @end smallexample
812 This function has undefined results if the strings overlap.
813 @end deftypefun
815 Programmers using the @code{strcat} or @code{wcscat} function (or the
816 following @code{strncat} or @code{wcsncar} functions for that matter)
817 can easily be recognized as lazy and reckless.  In almost all situations
818 the lengths of the participating strings are known (it better should be
819 since how can one otherwise ensure the allocated size of the buffer is
820 sufficient?)  Or at least, one could know them if one keeps track of the
821 results of the various function calls.  But then it is very inefficient
822 to use @code{strcat}/@code{wcscat}.  A lot of time is wasted finding the
823 end of the destination string so that the actual copying can start.
824 This is a common example:
826 @cindex __va_copy
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   /* @r{Actually @code{va_copy}, but this is the name more gcc versions}
841      @r{understand.}  */
842   __va_copy (ap2, ap);
844   /* @r{Determine how much space we need.}  */
845   for (s = str; s != NULL; s = va_arg (ap, const char *))
846     total += strlen (s);
848   va_end (ap);
850   result = (char *) malloc (total);
851   if (result != NULL)
852     @{
853       result[0] = '\0';
855       /* @r{Copy the strings.}  */
856       for (s = str; s != NULL; s = va_arg (ap2, const char *))
857         strcat (result, s);
858     @}
860   va_end (ap2);
862   return result;
864 @end smallexample
866 This looks quite simple, especially the second loop where the strings
867 are actually copied.  But these innocent lines hide a major performance
868 penalty.  Just imagine that ten strings of 100 bytes each have to be
869 concatenated.  For the second string we search the already stored 100
870 bytes for the end of the string so that we can append the next string.
871 For all strings in total the comparisons necessary to find the end of
872 the intermediate results sums up to 5500!  If we combine the copying
873 with the search for the allocation we can write this function more
874 efficient:
876 @smallexample
877 char *
878 concat (const char *str, @dots{})
880   va_list ap;
881   size_t allocated = 100;
882   char *result = (char *) malloc (allocated);
884   if (result != NULL)
885     @{
886       char *newp;
887       char *wp;
889       va_start (ap, str);
891       wp = result;
892       for (s = str; s != NULL; s = va_arg (ap, const char *))
893         @{
894           size_t len = strlen (s);
896           /* @r{Resize the allocated memory if necessary.}  */
897           if (wp + len + 1 > result + allocated)
898             @{
899               allocated = (allocated + len) * 2;
900               newp = (char *) realloc (result, allocated);
901               if (newp == NULL)
902                 @{
903                   free (result);
904                   return NULL;
905                 @}
906               wp = newp + (wp - result);
907               result = newp;
908             @}
910           wp = mempcpy (wp, s, len);
911         @}
913       /* @r{Terminate the result string.}  */
914       *wp++ = '\0';
916       /* @r{Resize memory to the optimal size.}  */
917       newp = realloc (result, wp - result);
918       if (newp != NULL)
919         result = newp;
921       va_end (ap);
922     @}
924   return result;
926 @end smallexample
928 With a bit more knowledge about the input strings one could fine-tune
929 the memory allocation.  The difference we are pointing to here is that
930 we don't use @code{strcat} anymore.  We always keep track of the length
931 of the current intermediate result so we can safe us the search for the
932 end of the string and use @code{mempcpy}.  Please note that we also
933 don't use @code{stpcpy} which might seem more natural since we handle
934 with strings.  But this is not necessary since we already know the
935 length of the string and therefore can use the faster memory copying
936 function.  The example would work for wide characters the same way.
938 Whenever a programmer feels the need to use @code{strcat} she or he
939 should think twice and look through the program whether the code cannot
940 be rewritten to take advantage of already calculated results.  Again: it
941 is almost always unnecessary to use @code{strcat}.
943 @comment string.h
944 @comment ISO
945 @deftypefun {char *} strncat (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
946 This function is like @code{strcat} except that not more than @var{size}
947 characters from @var{from} are appended to the end of @var{to}.  A
948 single null character is also always appended to @var{to}, so the total
949 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
950 longer than its initial length.
952 The @code{strncat} function could be implemented like this:
954 @smallexample
955 @group
956 char *
957 strncat (char *to, const char *from, size_t size)
959   to[strlen (to) + size] = '\0';
960   strncpy (to + strlen (to), from, size);
961   return to;
963 @end group
964 @end smallexample
966 The behavior of @code{strncat} is undefined if the strings overlap.
967 @end deftypefun
969 @comment wchar.h
970 @comment ISO
971 @deftypefun {wchar_t *} wcsncat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
972 This function is like @code{wcscat} except that not more than @var{size}
973 characters from @var{from} are appended to the end of @var{to}.  A
974 single null character is also always appended to @var{to}, so the total
975 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
976 longer than its initial length.
978 The @code{wcsncat} function could be implemented like this:
980 @smallexample
981 @group
982 wchar_t *
983 wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom,
984          size_t size)
986   wto[wcslen (to) + size] = L'\0';
987   wcsncpy (wto + wcslen (wto), wfrom, size);
988   return wto;
990 @end group
991 @end smallexample
993 The behavior of @code{wcsncat} is undefined if the strings overlap.
994 @end deftypefun
996 Here is an example showing the use of @code{strncpy} and @code{strncat}
997 (the wide character version is equivalent).  Notice how, in the call to
998 @code{strncat}, the @var{size} parameter is computed to avoid
999 overflowing the character array @code{buffer}.
1001 @smallexample
1002 @include strncat.c.texi
1003 @end smallexample
1005 @noindent
1006 The output produced by this program looks like:
1008 @smallexample
1009 hello
1010 hello, wo
1011 @end smallexample
1013 @comment string.h
1014 @comment BSD
1015 @deftypefun void bcopy (const void *@var{from}, void *@var{to}, size_t @var{size})
1016 This is a partially obsolete alternative for @code{memmove}, derived from
1017 BSD.  Note that it is not quite equivalent to @code{memmove}, because the
1018 arguments are not in the same order and there is no return value.
1019 @end deftypefun
1021 @comment string.h
1022 @comment BSD
1023 @deftypefun void bzero (void *@var{block}, size_t @var{size})
1024 This is a partially obsolete alternative for @code{memset}, derived from
1025 BSD.  Note that it is not as general as @code{memset}, because the only
1026 value it can store is zero.
1027 @end deftypefun
1029 @node String/Array Comparison
1030 @section String/Array Comparison
1031 @cindex comparing strings and arrays
1032 @cindex string comparison functions
1033 @cindex array comparison functions
1034 @cindex predicates on strings
1035 @cindex predicates on arrays
1037 You can use the functions in this section to perform comparisons on the
1038 contents of strings and arrays.  As well as checking for equality, these
1039 functions can also be used as the ordering functions for sorting
1040 operations.  @xref{Searching and Sorting}, for an example of this.
1042 Unlike most comparison operations in C, the string comparison functions
1043 return a nonzero value if the strings are @emph{not} equivalent rather
1044 than if they are.  The sign of the value indicates the relative ordering
1045 of the first characters in the strings that are not equivalent:  a
1046 negative value indicates that the first string is ``less'' than the
1047 second, while a positive value indicates that the first string is
1048 ``greater''.
1050 The most common use of these functions is to check only for equality.
1051 This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
1053 All of these functions are declared in the header file @file{string.h}.
1054 @pindex string.h
1056 @comment string.h
1057 @comment ISO
1058 @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
1059 The function @code{memcmp} compares the @var{size} bytes of memory
1060 beginning at @var{a1} against the @var{size} bytes of memory beginning
1061 at @var{a2}.  The value returned has the same sign as the difference
1062 between the first differing pair of bytes (interpreted as @code{unsigned
1063 char} objects, then promoted to @code{int}).
1065 If the contents of the two blocks are equal, @code{memcmp} returns
1066 @code{0}.
1067 @end deftypefun
1069 @comment wcjar.h
1070 @comment ISO
1071 @deftypefun int wmemcmp (const wchar_t *@var{a1}, const wchar_t *@var{a2}, size_t @var{size})
1072 The function @code{wmemcmp} compares the @var{size} wide characters
1073 beginning at @var{a1} against the @var{size} wide characters beginning
1074 at @var{a2}.  The value returned is smaller than or larger than zero
1075 depending on whether the first differing wide character is @var{a1} is
1076 smaller or larger than the corresponding character in @var{a2}.
1078 If the contents of the two blocks are equal, @code{wmemcmp} returns
1079 @code{0}.
1080 @end deftypefun
1082 On arbitrary arrays, the @code{memcmp} function is mostly useful for
1083 testing equality.  It usually isn't meaningful to do byte-wise ordering
1084 comparisons on arrays of things other than bytes.  For example, a
1085 byte-wise comparison on the bytes that make up floating-point numbers
1086 isn't likely to tell you anything about the relationship between the
1087 values of the floating-point numbers.
1089 @code{wmemcmp} is really only useful to compare arrays of type
1090 @code{wchar_t} since the function looks at @code{sizeof (wchar_t)} bytes
1091 at a time and this number of bytes is system dependent.
1093 You should also be careful about using @code{memcmp} to compare objects
1094 that can contain ``holes'', such as the padding inserted into structure
1095 objects to enforce alignment requirements, extra space at the end of
1096 unions, and extra characters at the ends of strings whose length is less
1097 than their allocated size.  The contents of these ``holes'' are
1098 indeterminate and may cause strange behavior when performing byte-wise
1099 comparisons.  For more predictable results, perform an explicit
1100 component-wise comparison.
1102 For example, given a structure type definition like:
1104 @smallexample
1105 struct foo
1106   @{
1107     unsigned char tag;
1108     union
1109       @{
1110         double f;
1111         long i;
1112         char *p;
1113       @} value;
1114   @};
1115 @end smallexample
1117 @noindent
1118 you are better off writing a specialized comparison function to compare
1119 @code{struct foo} objects instead of comparing them with @code{memcmp}.
1121 @comment string.h
1122 @comment ISO
1123 @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
1124 The @code{strcmp} function compares the string @var{s1} against
1125 @var{s2}, returning a value that has the same sign as the difference
1126 between the first differing pair of characters (interpreted as
1127 @code{unsigned char} objects, then promoted to @code{int}).
1129 If the two strings are equal, @code{strcmp} returns @code{0}.
1131 A consequence of the ordering used by @code{strcmp} is that if @var{s1}
1132 is an initial substring of @var{s2}, then @var{s1} is considered to be
1133 ``less than'' @var{s2}.
1135 @code{strcmp} does not take sorting conventions of the language the
1136 strings are written in into account.  To get that one has to use
1137 @code{strcoll}.
1138 @end deftypefun
1140 @comment wchar.h
1141 @comment ISO
1142 @deftypefun int wcscmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1144 The @code{wcscmp} function compares the wide character string @var{ws1}
1145 against @var{ws2}.  The value returned is smaller than or larger than zero
1146 depending on whether the first differing wide character is @var{ws1} is
1147 smaller or larger than the corresponding character in @var{ws2}.
1149 If the two strings are equal, @code{wcscmp} returns @code{0}.
1151 A consequence of the ordering used by @code{wcscmp} is that if @var{ws1}
1152 is an initial substring of @var{ws2}, then @var{ws1} is considered to be
1153 ``less than'' @var{ws2}.
1155 @code{wcscmp} does not take sorting conventions of the language the
1156 strings are written in into account.  To get that one has to use
1157 @code{wcscoll}.
1158 @end deftypefun
1160 @comment string.h
1161 @comment BSD
1162 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
1163 This function is like @code{strcmp}, except that differences in case are
1164 ignored.  How uppercase and lowercase characters are related is
1165 determined by the currently selected locale.  In the standard @code{"C"}
1166 locale the characters @"A and @"a do not match but in a locale which
1167 regards these characters as parts of the alphabet they do match.
1169 @noindent
1170 @code{strcasecmp} is derived from BSD.
1171 @end deftypefun
1173 @comment wchar.h
1174 @comment GNU
1175 @deftypefun int wcscasecmp (const wchar_t *@var{ws1}, const wchar_T *@var{ws2})
1176 This function is like @code{wcscmp}, except that differences in case are
1177 ignored.  How uppercase and lowercase characters are related is
1178 determined by the currently selected locale.  In the standard @code{"C"}
1179 locale the characters @"A and @"a do not match but in a locale which
1180 regards these characters as parts of the alphabet they do match.
1182 @noindent
1183 @code{wcscasecmp} is a GNU extension.
1184 @end deftypefun
1186 @comment string.h
1187 @comment ISO
1188 @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
1189 This function is the similar to @code{strcmp}, except that no more than
1190 @var{size} characters are compared.  In other words, if the two
1191 strings are the same in their first @var{size} characters, the
1192 return value is zero.
1193 @end deftypefun
1195 @comment wchar.h
1196 @comment ISO
1197 @deftypefun int wcsncmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2}, size_t @var{size})
1198 This function is the similar to @code{wcscmp}, except that no more than
1199 @var{size} wide characters are compared.  In other words, if the two
1200 strings are the same in their first @var{size} wide characters, the
1201 return value is zero.
1202 @end deftypefun
1204 @comment string.h
1205 @comment BSD
1206 @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
1207 This function is like @code{strncmp}, except that differences in case
1208 are ignored.  Like @code{strcasecmp}, it is locale dependent how
1209 uppercase and lowercase characters are related.
1211 @noindent
1212 @code{strncasecmp} is a GNU extension.
1213 @end deftypefun
1215 @comment wchar.h
1216 @comment GNU
1217 @deftypefun int wcsncasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{s2}, size_t @var{n})
1218 This function is like @code{wcsncmp}, except that differences in case
1219 are ignored.  Like @code{wcscasecmp}, it is locale dependent how
1220 uppercase and lowercase characters are related.
1222 @noindent
1223 @code{wcsncasecmp} is a GNU extension.
1224 @end deftypefun
1226 Here are some examples showing the use of @code{strcmp} and
1227 @code{strncmp} (equivalent examples can be constructed for the wide
1228 character functions).  These examples assume the use of the ASCII
1229 character set.  (If some other character set---say, EBCDIC---is used
1230 instead, then the glyphs are associated with different numeric codes,
1231 and the return values and ordering may differ.)
1233 @smallexample
1234 strcmp ("hello", "hello")
1235     @result{} 0    /* @r{These two strings are the same.} */
1236 strcmp ("hello", "Hello")
1237     @result{} 32   /* @r{Comparisons are case-sensitive.} */
1238 strcmp ("hello", "world")
1239     @result{} -15  /* @r{The character @code{'h'} comes before @code{'w'}.} */
1240 strcmp ("hello", "hello, world")
1241     @result{} -44  /* @r{Comparing a null character against a comma.} */
1242 strncmp ("hello", "hello, world", 5)
1243     @result{} 0    /* @r{The initial 5 characters are the same.} */
1244 strncmp ("hello, world", "hello, stupid world!!!", 5)
1245     @result{} 0    /* @r{The initial 5 characters are the same.} */
1246 @end smallexample
1248 @comment string.h
1249 @comment GNU
1250 @deftypefun int strverscmp (const char *@var{s1}, const char *@var{s2})
1251 The @code{strverscmp} function compares the string @var{s1} against
1252 @var{s2}, considering them as holding indices/version numbers.  Return
1253 value follows the same conventions as found in the @code{strverscmp}
1254 function.  In fact, if @var{s1} and @var{s2} contain no digits,
1255 @code{strverscmp} behaves like @code{strcmp}.
1257 Basically, we compare strings normally (character by character), until
1258 we find a digit in each string - then we enter a special comparison
1259 mode, where each sequence of digits is taken as a whole.  If we reach the
1260 end of these two parts without noticing a difference, we return to the
1261 standard comparison mode.  There are two types of numeric parts:
1262 "integral" and "fractional" (those  begin with a '0'). The types
1263 of the numeric parts affect the way we sort them:
1265 @itemize @bullet
1266 @item
1267 integral/integral: we compare values as you would expect.
1269 @item
1270 fractional/integral: the fractional part is less than the integral one.
1271 Again, no surprise.
1273 @item
1274 fractional/fractional: the things become a bit more complex.
1275 If the common prefix contains only leading zeroes, the longest part is less
1276 than the other one; else the comparison behaves normally.
1277 @end itemize
1279 @smallexample
1280 strverscmp ("no digit", "no digit")
1281     @result{} 0    /* @r{same behavior as strcmp.} */
1282 strverscmp ("item#99", "item#100")
1283     @result{} <0   /* @r{same prefix, but 99 < 100.} */
1284 strverscmp ("alpha1", "alpha001")
1285     @result{} >0   /* @r{fractional part inferior to integral one.} */
1286 strverscmp ("part1_f012", "part1_f01")
1287     @result{} >0   /* @r{two fractional parts.} */
1288 strverscmp ("foo.009", "foo.0")
1289     @result{} <0   /* @r{idem, but with leading zeroes only.} */
1290 @end smallexample
1292 This function is especially useful when dealing with filename sorting,
1293 because filenames frequently hold indices/version numbers.
1295 @code{strverscmp} is a GNU extension.
1296 @end deftypefun
1298 @comment string.h
1299 @comment BSD
1300 @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
1301 This is an obsolete alias for @code{memcmp}, derived from BSD.
1302 @end deftypefun
1304 @node Collation Functions
1305 @section Collation Functions
1307 @cindex collating strings
1308 @cindex string collation functions
1310 In some locales, the conventions for lexicographic ordering differ from
1311 the strict numeric ordering of character codes.  For example, in Spanish
1312 most glyphs with diacritical marks such as accents are not considered
1313 distinct letters for the purposes of collation.  On the other hand, the
1314 two-character sequence @samp{ll} is treated as a single letter that is
1315 collated immediately after @samp{l}.
1317 You can use the functions @code{strcoll} and @code{strxfrm} (declared in
1318 the headers file @file{string.h}) and @code{wcscoll} and @code{wcsxfrm}
1319 (declared in the headers file @file{wchar}) to compare strings using a
1320 collation ordering appropriate for the current locale.  The locale used
1321 by these functions in particular can be specified by setting the locale
1322 for the @code{LC_COLLATE} category; see @ref{Locales}.
1323 @pindex string.h
1324 @pindex wchar.h
1326 In the standard C locale, the collation sequence for @code{strcoll} is
1327 the same as that for @code{strcmp}.  Similarly, @code{wcscoll} and
1328 @code{wcscmp} are the same in this situation.
1330 Effectively, the way these functions work is by applying a mapping to
1331 transform the characters in a string to a byte sequence that represents
1332 the string's position in the collating sequence of the current locale.
1333 Comparing two such byte sequences in a simple fashion is equivalent to
1334 comparing the strings with the locale's collating sequence.
1336 The functions @code{strcoll} and @code{wcscoll} perform this translation
1337 implicitly, in order to do one comparison.  By contrast, @code{strxfrm}
1338 and @code{wcsxfrm} perform the mapping explicitly.  If you are making
1339 multiple comparisons using the same string or set of strings, it is
1340 likely to be more efficient to use @code{strxfrm} or @code{wcsxfrm} to
1341 transform all the strings just once, and subsequently compare the
1342 transformed strings with @code{strcmp} or @code{wcscmp}.
1344 @comment string.h
1345 @comment ISO
1346 @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
1347 The @code{strcoll} function is similar to @code{strcmp} but uses the
1348 collating sequence of the current locale for collation (the
1349 @code{LC_COLLATE} locale).
1350 @end deftypefun
1352 @comment wchar.h
1353 @comment ISO
1354 @deftypefun int wcscoll (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1355 The @code{wcscoll} function is similar to @code{wcscmp} but uses the
1356 collating sequence of the current locale for collation (the
1357 @code{LC_COLLATE} locale).
1358 @end deftypefun
1360 Here is an example of sorting an array of strings, using @code{strcoll}
1361 to compare them.  The actual sort algorithm is not written here; it
1362 comes from @code{qsort} (@pxref{Array Sort Function}).  The job of the
1363 code shown here is to say how to compare the strings while sorting them.
1364 (Later on in this section, we will show a way to do this more
1365 efficiently using @code{strxfrm}.)
1367 @smallexample
1368 /* @r{This is the comparison function used with @code{qsort}.} */
1371 compare_elements (char **p1, char **p2)
1373   return strcoll (*p1, *p2);
1376 /* @r{This is the entry point---the function to sort}
1377    @r{strings using the locale's collating sequence.} */
1379 void
1380 sort_strings (char **array, int nstrings)
1382   /* @r{Sort @code{temp_array} by comparing the strings.} */
1383   qsort (array, nstrings,
1384          sizeof (char *), compare_elements);
1386 @end smallexample
1388 @cindex converting string to collation order
1389 @comment string.h
1390 @comment ISO
1391 @deftypefun size_t strxfrm (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
1392 The function @code{strxfrm} transforms the string @var{from} using the
1393 collation transformation determined by the locale currently selected for
1394 collation, and stores the transformed string in the array @var{to}.  Up
1395 to @var{size} characters (including a terminating null character) are
1396 stored.
1398 The behavior is undefined if the strings @var{to} and @var{from}
1399 overlap; see @ref{Copying and Concatenation}.
1401 The return value is the length of the entire transformed string.  This
1402 value is not affected by the value of @var{size}, but if it is greater
1403 or equal than @var{size}, it means that the transformed string did not
1404 entirely fit in the array @var{to}.  In this case, only as much of the
1405 string as actually fits was stored.  To get the whole transformed
1406 string, call @code{strxfrm} again with a bigger output array.
1408 The transformed string may be longer than the original string, and it
1409 may also be shorter.
1411 If @var{size} is zero, no characters are stored in @var{to}.  In this
1412 case, @code{strxfrm} simply returns the number of characters that would
1413 be the length of the transformed string.  This is useful for determining
1414 what size the allocated array should be.  It does not matter what
1415 @var{to} is if @var{size} is zero; @var{to} may even be a null pointer.
1416 @end deftypefun
1418 @comment wchar.h
1419 @comment ISO
1420 @deftypefun size_t wcsxfrm (wchar_t *restrict @var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
1421 The function @code{wcsxfrm} transforms wide character string @var{wfrom}
1422 using the collation transformation determined by the locale currently
1423 selected for collation, and stores the transformed string in the array
1424 @var{wto}.  Up to @var{size} wide characters (including a terminating null
1425 character) are stored.
1427 The behavior is undefined if the strings @var{wto} and @var{wfrom}
1428 overlap; see @ref{Copying and Concatenation}.
1430 The return value is the length of the entire transformed wide character
1431 string.  This value is not affected by the value of @var{size}, but if
1432 it is greater or equal than @var{size}, it means that the transformed
1433 wide character string did not entirely fit in the array @var{wto}.  In
1434 this case, only as much of the wide character string as actually fits
1435 was stored.  To get the whole transformed wide character string, call
1436 @code{wcsxfrm} again with a bigger output array.
1438 The transformed wide character string may be longer than the original
1439 wide character string, and it may also be shorter.
1441 If @var{size} is zero, no characters are stored in @var{to}.  In this
1442 case, @code{wcsxfrm} simply returns the number of wide characters that
1443 would be the length of the transformed wide character string.  This is
1444 useful for determining what size the allocated array should be (remember
1445 to multiply with @code{sizeof (wchar_t)}).  It does not matter what
1446 @var{wto} is if @var{size} is zero; @var{wto} may even be a null pointer.
1447 @end deftypefun
1449 Here is an example of how you can use @code{strxfrm} when
1450 you plan to do many comparisons.  It does the same thing as the previous
1451 example, but much faster, because it has to transform each string only
1452 once, no matter how many times it is compared with other strings.  Even
1453 the time needed to allocate and free storage is much less than the time
1454 we save, when there are many strings.
1456 @smallexample
1457 struct sorter @{ char *input; char *transformed; @};
1459 /* @r{This is the comparison function used with @code{qsort}}
1460    @r{to sort an array of @code{struct sorter}.} */
1463 compare_elements (struct sorter *p1, struct sorter *p2)
1465   return strcmp (p1->transformed, p2->transformed);
1468 /* @r{This is the entry point---the function to sort}
1469    @r{strings using the locale's collating sequence.} */
1471 void
1472 sort_strings_fast (char **array, int nstrings)
1474   struct sorter temp_array[nstrings];
1475   int i;
1477   /* @r{Set up @code{temp_array}.  Each element contains}
1478      @r{one input string and its transformed string.} */
1479   for (i = 0; i < nstrings; i++)
1480     @{
1481       size_t length = strlen (array[i]) * 2;
1482       char *transformed;
1483       size_t transformed_length;
1485       temp_array[i].input = array[i];
1487       /* @r{First try a buffer perhaps big enough.}  */
1488       transformed = (char *) xmalloc (length);
1490       /* @r{Transform @code{array[i]}.}  */
1491       transformed_length = strxfrm (transformed, array[i], length);
1493       /* @r{If the buffer was not large enough, resize it}
1494          @r{and try again.}  */
1495       if (transformed_length >= length)
1496         @{
1497           /* @r{Allocate the needed space. +1 for terminating}
1498              @r{@code{NUL} character.}  */
1499           transformed = (char *) xrealloc (transformed,
1500                                            transformed_length + 1);
1502           /* @r{The return value is not interesting because we know}
1503              @r{how long the transformed string is.}  */
1504           (void) strxfrm (transformed, array[i],
1505                           transformed_length + 1);
1506         @}
1508       temp_array[i].transformed = transformed;
1509     @}
1511   /* @r{Sort @code{temp_array} by comparing transformed strings.} */
1512   qsort (temp_array, sizeof (struct sorter),
1513          nstrings, compare_elements);
1515   /* @r{Put the elements back in the permanent array}
1516      @r{in their sorted order.} */
1517   for (i = 0; i < nstrings; i++)
1518     array[i] = temp_array[i].input;
1520   /* @r{Free the strings we allocated.} */
1521   for (i = 0; i < nstrings; i++)
1522     free (temp_array[i].transformed);
1524 @end smallexample
1526 The interesting part of this code for the wide character version would
1527 look like this:
1529 @smallexample
1530 void
1531 sort_strings_fast (wchar_t **array, int nstrings)
1533   @dots{}
1534       /* @r{Transform @code{array[i]}.}  */
1535       transformed_length = wcsxfrm (transformed, array[i], length);
1537       /* @r{If the buffer was not large enough, resize it}
1538          @r{and try again.}  */
1539       if (transformed_length >= length)
1540         @{
1541           /* @r{Allocate the needed space. +1 for terminating}
1542              @r{@code{NUL} character.}  */
1543           transformed = (wchar_t *) xrealloc (transformed,
1544                                               (transformed_length + 1)
1545                                               * sizeof (wchar_t));
1547           /* @r{The return value is not interesting because we know}
1548              @r{how long the transformed string is.}  */
1549           (void) wcsxfrm (transformed, array[i],
1550                           transformed_length + 1);
1551         @}
1552   @dots{}
1553 @end smallexample
1555 @noindent
1556 Note the additional multiplication with @code{sizeof (wchar_t)} in the
1557 @code{realloc} call.
1559 @strong{Compatibility Note:} The string collation functions are a new
1560 feature of @w{ISO C90}.  Older C dialects have no equivalent feature.
1561 The wide character versions were introduced in @w{Amendment 1} to @w{ISO
1562 C90}.
1564 @node Search Functions
1565 @section Search Functions
1567 This section describes library functions which perform various kinds
1568 of searching operations on strings and arrays.  These functions are
1569 declared in the header file @file{string.h}.
1570 @pindex string.h
1571 @cindex search functions (for strings)
1572 @cindex string search functions
1574 @comment string.h
1575 @comment ISO
1576 @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
1577 This function finds the first occurrence of the byte @var{c} (converted
1578 to an @code{unsigned char}) in the initial @var{size} bytes of the
1579 object beginning at @var{block}.  The return value is a pointer to the
1580 located byte, or a null pointer if no match was found.
1581 @end deftypefun
1583 @comment wchar.h
1584 @comment ISO
1585 @deftypefun {wchar_t *} wmemchr (const wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
1586 This function finds the first occurrence of the wide character @var{wc}
1587 in the initial @var{size} wide characters of the object beginning at
1588 @var{block}.  The return value is a pointer to the located wide
1589 character, or a null pointer if no match was found.
1590 @end deftypefun
1592 @comment string.h
1593 @comment GNU
1594 @deftypefun {void *} rawmemchr (const void *@var{block}, int @var{c})
1595 Often the @code{memchr} function is used with the knowledge that the
1596 byte @var{c} is available in the memory block specified by the
1597 parameters.  But this means that the @var{size} parameter is not really
1598 needed and that the tests performed with it at runtime (to check whether
1599 the end of the block is reached) are not needed.
1601 The @code{rawmemchr} function exists for just this situation which is
1602 surprisingly frequent.  The interface is similar to @code{memchr} except
1603 that the @var{size} parameter is missing.  The function will look beyond
1604 the end of the block pointed to by @var{block} in case the programmer
1605 made an error in assuming that the byte @var{c} is present in the block.
1606 In this case the result is unspecified.  Otherwise the return value is a
1607 pointer to the located byte.
1609 This function is of special interest when looking for the end of a
1610 string.  Since all strings are terminated by a null byte a call like
1612 @smallexample
1613    rawmemchr (str, '\0')
1614 @end smallexample
1616 @noindent
1617 will never go beyond the end of the string.
1619 This function is a GNU extension.
1620 @end deftypefun
1622 @comment string.h
1623 @comment GNU
1624 @deftypefun {void *} memrchr (const void *@var{block}, int @var{c}, size_t @var{size})
1625 The function @code{memrchr} is like @code{memchr}, except that it searches
1626 backwards from the end of the block defined by @var{block} and @var{size}
1627 (instead of forwards from the front).
1629 This function is a GNU extension.
1630 @end deftypefun
1632 @comment string.h
1633 @comment ISO
1634 @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
1635 The @code{strchr} function finds the first occurrence of the character
1636 @var{c} (converted to a @code{char}) in the null-terminated string
1637 beginning at @var{string}.  The return value is a pointer to the located
1638 character, or a null pointer if no match was found.
1640 For example,
1641 @smallexample
1642 strchr ("hello, world", 'l')
1643     @result{} "llo, world"
1644 strchr ("hello, world", '?')
1645     @result{} NULL
1646 @end smallexample
1648 The terminating null character is considered to be part of the string,
1649 so you can use this function get a pointer to the end of a string by
1650 specifying a null character as the value of the @var{c} argument.  It
1651 would be better (but less portable) to use @code{strchrnul} in this
1652 case, though.
1653 @end deftypefun
1655 @comment wchar.h
1656 @comment ISO
1657 @deftypefun {wchar_t *} wcschr (const wchar_t *@var{wstring}, int @var{wc})
1658 The @code{wcschr} function finds the first occurrence of the wide
1659 character @var{wc} in the null-terminated wide character string
1660 beginning at @var{wstring}.  The return value is a pointer to the
1661 located wide character, or a null pointer if no match was found.
1663 The terminating null character is considered to be part of the wide
1664 character string, so you can use this function get a pointer to the end
1665 of a wide character string by specifying a null wude character as the
1666 value of the @var{wc} argument.  It would be better (but less portable)
1667 to use @code{wcschrnul} in this case, though.
1668 @end deftypefun
1670 @comment string.h
1671 @comment GNU
1672 @deftypefun {char *} strchrnul (const char *@var{string}, int @var{c})
1673 @code{strchrnul} is the same as @code{strchr} except that if it does
1674 not find the character, it returns a pointer to string's terminating
1675 null character rather than a null pointer.
1677 This function is a GNU extension.
1678 @end deftypefun
1680 @comment wchar.h
1681 @comment GNU
1682 @deftypefun {wchar_t *} wcschrnul (const wchar_t *@var{wstring}, wchar_t @var{wc})
1683 @code{wcschrnul} is the same as @code{wcschr} except that if it does not
1684 find the wide character, it returns a pointer to wide character string's
1685 terminating null wide character rather than a null pointer.
1687 This function is a GNU extension.
1688 @end deftypefun
1690 One useful, but unusual, use of the @code{strchr}
1691 function is when one wants to have a pointer pointing to the NUL byte
1692 terminating a string.  This is often written in this way:
1694 @smallexample
1695   s += strlen (s);
1696 @end smallexample
1698 @noindent
1699 This is almost optimal but the addition operation duplicated a bit of
1700 the work already done in the @code{strlen} function.  A better solution
1701 is this:
1703 @smallexample
1704   s = strchr (s, '\0');
1705 @end smallexample
1707 There is no restriction on the second parameter of @code{strchr} so it
1708 could very well also be the NUL character.  Those readers thinking very
1709 hard about this might now point out that the @code{strchr} function is
1710 more expensive than the @code{strlen} function since we have two abort
1711 criteria.  This is right.  But in the GNU C library the implementation of
1712 @code{strchr} is optimized in a special way so that @code{strchr}
1713 actually is faster.
1715 @comment string.h
1716 @comment ISO
1717 @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
1718 The function @code{strrchr} is like @code{strchr}, except that it searches
1719 backwards from the end of the string @var{string} (instead of forwards
1720 from the front).
1722 For example,
1723 @smallexample
1724 strrchr ("hello, world", 'l')
1725     @result{} "ld"
1726 @end smallexample
1727 @end deftypefun
1729 @comment wchar.h
1730 @comment ISO
1731 @deftypefun {wchar_t *} wcsrchr (const wchar_t *@var{wstring}, wchar_t @var{c})
1732 The function @code{wcsrchr} is like @code{wcschr}, except that it searches
1733 backwards from the end of the string @var{wstring} (instead of forwards
1734 from the front).
1735 @end deftypefun
1737 @comment string.h
1738 @comment ISO
1739 @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
1740 This is like @code{strchr}, except that it searches @var{haystack} for a
1741 substring @var{needle} rather than just a single character.  It
1742 returns a pointer into the string @var{haystack} that is the first
1743 character of the substring, or a null pointer if no match was found.  If
1744 @var{needle} is an empty string, the function returns @var{haystack}.
1746 For example,
1747 @smallexample
1748 strstr ("hello, world", "l")
1749     @result{} "llo, world"
1750 strstr ("hello, world", "wo")
1751     @result{} "world"
1752 @end smallexample
1753 @end deftypefun
1755 @comment wchar.h
1756 @comment ISO
1757 @deftypefun {wchar_t *} wcsstr (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
1758 This is like @code{wcschr}, except that it searches @var{haystack} for a
1759 substring @var{needle} rather than just a single wide character.  It
1760 returns a pointer into the string @var{haystack} that is the first wide
1761 character of the substring, or a null pointer if no match was found.  If
1762 @var{needle} is an empty string, the function returns @var{haystack}.
1763 @end deftypefun
1765 @comment wchar.h
1766 @comment XPG
1767 @deftypefun {wchar_t *} wcswcs (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
1768 @code{wcswcs} is an deprecated alias for @code{wcsstr}.  This is the
1769 name originally used in the X/Open Portability Guide before the
1770 @w{Amendment 1} to @w{ISO C90} was published.
1771 @end deftypefun
1774 @comment string.h
1775 @comment GNU
1776 @deftypefun {char *} strcasestr (const char *@var{haystack}, const char *@var{needle})
1777 This is like @code{strstr}, except that it ignores case in searching for
1778 the substring.   Like @code{strcasecmp}, it is locale dependent how
1779 uppercase and lowercase characters are related.
1782 For example,
1783 @smallexample
1784 strcasestr ("hello, world", "L")
1785     @result{} "llo, world"
1786 strcasestr ("hello, World", "wo")
1787     @result{} "World"
1788 @end smallexample
1789 @end deftypefun
1792 @comment string.h
1793 @comment GNU
1794 @deftypefun {void *} memmem (const void *@var{haystack}, size_t @var{haystack-len},@*const void *@var{needle}, size_t @var{needle-len})
1795 This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
1796 arrays rather than null-terminated strings.  @var{needle-len} is the
1797 length of @var{needle} and @var{haystack-len} is the length of
1798 @var{haystack}.@refill
1800 This function is a GNU extension.
1801 @end deftypefun
1803 @comment string.h
1804 @comment ISO
1805 @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
1806 The @code{strspn} (``string span'') function returns the length of the
1807 initial substring of @var{string} that consists entirely of characters that
1808 are members of the set specified by the string @var{skipset}.  The order
1809 of the characters in @var{skipset} is not important.
1811 For example,
1812 @smallexample
1813 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
1814     @result{} 5
1815 @end smallexample
1817 Note that ``character'' is here used in the sense of byte.  In a string
1818 using a multibyte character encoding (abstract) character consisting of
1819 more than one byte are not treated as an entity.  Each byte is treated
1820 separately.  The function is not locale-dependent.
1821 @end deftypefun
1823 @comment wchar.h
1824 @comment ISO
1825 @deftypefun size_t wcsspn (const wchar_t *@var{wstring}, const wchar_t *@var{skipset})
1826 The @code{wcsspn} (``wide character string span'') function returns the
1827 length of the initial substring of @var{wstring} that consists entirely
1828 of wide characters that are members of the set specified by the string
1829 @var{skipset}.  The order of the wide characters in @var{skipset} is not
1830 important.
1831 @end deftypefun
1833 @comment string.h
1834 @comment ISO
1835 @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
1836 The @code{strcspn} (``string complement span'') function returns the length
1837 of the initial substring of @var{string} that consists entirely of characters
1838 that are @emph{not} members of the set specified by the string @var{stopset}.
1839 (In other words, it returns the offset of the first character in @var{string}
1840 that is a member of the set @var{stopset}.)
1842 For example,
1843 @smallexample
1844 strcspn ("hello, world", " \t\n,.;!?")
1845     @result{} 5
1846 @end smallexample
1848 Note that ``character'' is here used in the sense of byte.  In a string
1849 using a multibyte character encoding (abstract) character consisting of
1850 more than one byte are not treated as an entity.  Each byte is treated
1851 separately.  The function is not locale-dependent.
1852 @end deftypefun
1854 @comment wchar.h
1855 @comment ISO
1856 @deftypefun size_t wcscspn (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
1857 The @code{wcscspn} (``wide character string complement span'') function
1858 returns the length of the initial substring of @var{wstring} that
1859 consists entirely of wide characters that are @emph{not} members of the
1860 set specified by the string @var{stopset}.  (In other words, it returns
1861 the offset of the first character in @var{string} that is a member of
1862 the set @var{stopset}.)
1863 @end deftypefun
1865 @comment string.h
1866 @comment ISO
1867 @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
1868 The @code{strpbrk} (``string pointer break'') function is related to
1869 @code{strcspn}, except that it returns a pointer to the first character
1870 in @var{string} that is a member of the set @var{stopset} instead of the
1871 length of the initial substring.  It returns a null pointer if no such
1872 character from @var{stopset} is found.
1874 @c @group  Invalid outside the example.
1875 For example,
1877 @smallexample
1878 strpbrk ("hello, world", " \t\n,.;!?")
1879     @result{} ", world"
1880 @end smallexample
1881 @c @end group
1883 Note that ``character'' is here used in the sense of byte.  In a string
1884 using a multibyte character encoding (abstract) character consisting of
1885 more than one byte are not treated as an entity.  Each byte is treated
1886 separately.  The function is not locale-dependent.
1887 @end deftypefun
1889 @comment wchar.h
1890 @comment ISO
1891 @deftypefun {wchar_t *} wcspbrk (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
1892 The @code{wcspbrk} (``wide character string pointer break'') function is
1893 related to @code{wcscspn}, except that it returns a pointer to the first
1894 wide character in @var{wstring} that is a member of the set
1895 @var{stopset} instead of the length of the initial substring.  It
1896 returns a null pointer if no such character from @var{stopset} is found.
1897 @end deftypefun
1900 @subsection Compatibility String Search Functions
1902 @comment string.h
1903 @comment BSD
1904 @deftypefun {char *} index (const char *@var{string}, int @var{c})
1905 @code{index} is another name for @code{strchr}; they are exactly the same.
1906 New code should always use @code{strchr} since this name is defined in
1907 @w{ISO C} while @code{index} is a BSD invention which never was available
1908 on @w{System V} derived systems.
1909 @end deftypefun
1911 @comment string.h
1912 @comment BSD
1913 @deftypefun {char *} rindex (const char *@var{string}, int @var{c})
1914 @code{rindex} is another name for @code{strrchr}; they are exactly the same.
1915 New code should always use @code{strrchr} since this name is defined in
1916 @w{ISO C} while @code{rindex} is a BSD invention which never was available
1917 on @w{System V} derived systems.
1918 @end deftypefun
1920 @node Finding Tokens in a String
1921 @section Finding Tokens in a String
1923 @cindex tokenizing strings
1924 @cindex breaking a string into tokens
1925 @cindex parsing tokens from a string
1926 It's fairly common for programs to have a need to do some simple kinds
1927 of lexical analysis and parsing, such as splitting a command string up
1928 into tokens.  You can do this with the @code{strtok} function, declared
1929 in the header file @file{string.h}.
1930 @pindex string.h
1932 @comment string.h
1933 @comment ISO
1934 @deftypefun {char *} strtok (char *restrict @var{newstring}, const char *restrict @var{delimiters})
1935 A string can be split into tokens by making a series of calls to the
1936 function @code{strtok}.
1938 The string to be split up is passed as the @var{newstring} argument on
1939 the first call only.  The @code{strtok} function uses this to set up
1940 some internal state information.  Subsequent calls to get additional
1941 tokens from the same string are indicated by passing a null pointer as
1942 the @var{newstring} argument.  Calling @code{strtok} with another
1943 non-null @var{newstring} argument reinitializes the state information.
1944 It is guaranteed that no other library function ever calls @code{strtok}
1945 behind your back (which would mess up this internal state information).
1947 The @var{delimiters} argument is a string that specifies a set of delimiters
1948 that may surround the token being extracted.  All the initial characters
1949 that are members of this set are discarded.  The first character that is
1950 @emph{not} a member of this set of delimiters marks the beginning of the
1951 next token.  The end of the token is found by looking for the next
1952 character that is a member of the delimiter set.  This character in the
1953 original string @var{newstring} is overwritten by a null character, and the
1954 pointer to the beginning of the token in @var{newstring} is returned.
1956 On the next call to @code{strtok}, the searching begins at the next
1957 character beyond the one that marked the end of the previous token.
1958 Note that the set of delimiters @var{delimiters} do not have to be the
1959 same on every call in a series of calls to @code{strtok}.
1961 If the end of the string @var{newstring} is reached, or if the remainder of
1962 string consists only of delimiter characters, @code{strtok} returns
1963 a null pointer.
1965 Note that ``character'' is here used in the sense of byte.  In a string
1966 using a multibyte character encoding (abstract) character consisting of
1967 more than one byte are not treated as an entity.  Each byte is treated
1968 separately.  The function is not locale-dependent.
1969 @end deftypefun
1971 @comment wchar.h
1972 @comment ISO
1973 @deftypefun {wchar_t *} wcstok (wchar_t *@var{newstring}, const char *@var{delimiters})
1974 A string can be split into tokens by making a series of calls to the
1975 function @code{wcstok}.
1977 The string to be split up is passed as the @var{newstring} argument on
1978 the first call only.  The @code{wcstok} function uses this to set up
1979 some internal state information.  Subsequent calls to get additional
1980 tokens from the same wide character string are indicated by passing a
1981 null pointer as the @var{newstring} argument.  Calling @code{wcstok}
1982 with another non-null @var{newstring} argument reinitializes the state
1983 information.  It is guaranteed that no other library function ever calls
1984 @code{wcstok} behind your back (which would mess up this internal state
1985 information).
1987 The @var{delimiters} argument is a wide character string that specifies
1988 a set of delimiters that may surround the token being extracted.  All
1989 the initial wide characters that are members of this set are discarded.
1990 The first wide character that is @emph{not} a member of this set of
1991 delimiters marks the beginning of the next token.  The end of the token
1992 is found by looking for the next wide character that is a member of the
1993 delimiter set.  This wide character in the original wide character
1994 string @var{newstring} is overwritten by a null wide character, and the
1995 pointer to the beginning of the token in @var{newstring} is returned.
1997 On the next call to @code{wcstok}, the searching begins at the next
1998 wide character beyond the one that marked the end of the previous token.
1999 Note that the set of delimiters @var{delimiters} do not have to be the
2000 same on every call in a series of calls to @code{wcstok}.
2002 If the end of the wide character string @var{newstring} is reached, or
2003 if the remainder of string consists only of delimiter wide characters,
2004 @code{wcstok} returns a null pointer.
2006 Note that ``character'' is here used in the sense of byte.  In a string
2007 using a multibyte character encoding (abstract) character consisting of
2008 more than one byte are not treated as an entity.  Each byte is treated
2009 separately.  The function is not locale-dependent.
2010 @end deftypefun
2012 @strong{Warning:} Since @code{strtok} and @code{wcstok} alter the string
2013 they is parsing, you should always copy the string to a temporary buffer
2014 before parsing it with @code{strtok}/@code{wcstok} (@pxref{Copying and
2015 Concatenation}).  If you allow @code{strtok} or @code{wcstok} to modify
2016 a string that came from another part of your program, you are asking for
2017 trouble; that string might be used for other purposes after
2018 @code{strtok} or @code{wcstok} has modified it, and it would not have
2019 the expected value.
2021 The string that you are operating on might even be a constant.  Then
2022 when @code{strtok} or @code{wcstok} tries to modify it, your program
2023 will get a fatal signal for writing in read-only memory.  @xref{Program
2024 Error Signals}.  Even if the operation of @code{strtok} or @code{wcstok}
2025 would not require a modification of the string (e.g., if there is
2026 exactly one token) the string can (and in the GNU libc case will) be
2027 modified.
2029 This is a special case of a general principle: if a part of a program
2030 does not have as its purpose the modification of a certain data
2031 structure, then it is error-prone to modify the data structure
2032 temporarily.
2034 The functions @code{strtok} and @code{wcstok} are not reentrant.
2035 @xref{Nonreentrancy}, for a discussion of where and why reentrancy is
2036 important.
2038 Here is a simple example showing the use of @code{strtok}.
2040 @comment Yes, this example has been tested.
2041 @smallexample
2042 #include <string.h>
2043 #include <stddef.h>
2045 @dots{}
2047 const char string[] = "words separated by spaces -- and, punctuation!";
2048 const char delimiters[] = " .,;:!-";
2049 char *token, *cp;
2051 @dots{}
2053 cp = strdupa (string);                /* Make writable copy.  */
2054 token = strtok (cp, delimiters);      /* token => "words" */
2055 token = strtok (NULL, delimiters);    /* token => "separated" */
2056 token = strtok (NULL, delimiters);    /* token => "by" */
2057 token = strtok (NULL, delimiters);    /* token => "spaces" */
2058 token = strtok (NULL, delimiters);    /* token => "and" */
2059 token = strtok (NULL, delimiters);    /* token => "punctuation" */
2060 token = strtok (NULL, delimiters);    /* token => NULL */
2061 @end smallexample
2063 The GNU C library contains two more functions for tokenizing a string
2064 which overcome the limitation of non-reentrancy.  They are only
2065 available for multibyte character strings.
2067 @comment string.h
2068 @comment POSIX
2069 @deftypefun {char *} strtok_r (char *@var{newstring}, const char *@var{delimiters}, char **@var{save_ptr})
2070 Just like @code{strtok}, this function splits the string into several
2071 tokens which can be accessed by successive calls to @code{strtok_r}.
2072 The difference is that the information about the next token is stored in
2073 the space pointed to by the third argument, @var{save_ptr}, which is a
2074 pointer to a string pointer.  Calling @code{strtok_r} with a null
2075 pointer for @var{newstring} and leaving @var{save_ptr} between the calls
2076 unchanged does the job without hindering reentrancy.
2078 This function is defined in POSIX.1 and can be found on many systems
2079 which support multi-threading.
2080 @end deftypefun
2082 @comment string.h
2083 @comment BSD
2084 @deftypefun {char *} strsep (char **@var{string_ptr}, const char *@var{delimiter})
2085 This function has a similar functionality as @code{strtok_r} with the
2086 @var{newstring} argument replaced by the @var{save_ptr} argument.  The
2087 initialization of the moving pointer has to be done by the user.
2088 Successive calls to @code{strsep} move the pointer along the tokens
2089 separated by @var{delimiter}, returning the address of the next token
2090 and updating @var{string_ptr} to point to the beginning of the next
2091 token.
2093 One difference between @code{strsep} and @code{strtok_r} is that if the
2094 input string contains more than one character from @var{delimiter} in a
2095 row @code{strsep} returns an empty string for each pair of characters
2096 from @var{delimiter}.  This means that a program normally should test
2097 for @code{strsep} returning an empty string before processing it.
2099 This function was introduced in 4.3BSD and therefore is widely available.
2100 @end deftypefun
2102 Here is how the above example looks like when @code{strsep} is used.
2104 @comment Yes, this example has been tested.
2105 @smallexample
2106 #include <string.h>
2107 #include <stddef.h>
2109 @dots{}
2111 const char string[] = "words separated by spaces -- and, punctuation!";
2112 const char delimiters[] = " .,;:!-";
2113 char *running;
2114 char *token;
2116 @dots{}
2118 running = strdupa (string);
2119 token = strsep (&running, delimiters);    /* token => "words" */
2120 token = strsep (&running, delimiters);    /* token => "separated" */
2121 token = strsep (&running, delimiters);    /* token => "by" */
2122 token = strsep (&running, delimiters);    /* token => "spaces" */
2123 token = strsep (&running, delimiters);    /* token => "" */
2124 token = strsep (&running, delimiters);    /* token => "" */
2125 token = strsep (&running, delimiters);    /* token => "" */
2126 token = strsep (&running, delimiters);    /* token => "and" */
2127 token = strsep (&running, delimiters);    /* token => "" */
2128 token = strsep (&running, delimiters);    /* token => "punctuation" */
2129 token = strsep (&running, delimiters);    /* token => "" */
2130 token = strsep (&running, delimiters);    /* token => NULL */
2131 @end smallexample
2133 @comment string.h
2134 @comment GNU
2135 @deftypefun {char *} basename (const char *@var{filename})
2136 The GNU version of the @code{basename} function returns the last
2137 component of the path in @var{filename}.  This function is the preferred
2138 usage, since it does not modify the argument, @var{filename}, and
2139 respects trailing slashes.  The prototype for @code{basename} can be
2140 found in @file{string.h}.  Note, this function is overriden by the XPG
2141 version, if @file{libgen.h} is included.
2143 Example of using GNU @code{basename}:
2145 @smallexample
2146 #include <string.h>
2149 main (int argc, char *argv[])
2151   char *prog = basename (argv[0]);
2153   if (argc < 2)
2154     @{
2155       fprintf (stderr, "Usage %s <arg>\n", prog);
2156       exit (1);
2157     @}
2159   @dots{}
2161 @end smallexample
2163 @strong{Portability Note:} This function may produce different results
2164 on different systems.
2166 @end deftypefun
2168 @comment libgen.h
2169 @comment XPG
2170 @deftypefun {char *} basename (char *@var{path})
2171 This is the standard XPG defined @code{basename}. It is similar in
2172 spirit to the GNU version, but may modify the @var{path} by removing
2173 trailing '/' characters.  If the @var{path} is made up entirely of '/'
2174 characters, then "/" will be returned.  Also, if @var{path} is
2175 @code{NULL} or an empty string, then "." is returned.  The prototype for
2176 the XPG version can be found in @file{libgen.h}.
2178 Example of using XPG @code{basename}:
2180 @smallexample
2181 #include <libgen.h>
2184 main (int argc, char *argv[])
2186   char *prog;
2187   char *path = strdupa (argv[0]);
2189   prog = basename (path);
2191   if (argc < 2)
2192     @{
2193       fprintf (stderr, "Usage %s <arg>\n", prog);
2194       exit (1);
2195     @}
2197   @dots{}
2200 @end smallexample
2201 @end deftypefun
2203 @comment libgen.h
2204 @comment XPG
2205 @deftypefun {char *} dirname (char *@var{path})
2206 The @code{dirname} function is the compliment to the XPG version of
2207 @code{basename}.  It returns the parent directory of the file specified
2208 by @var{path}.  If @var{path} is @code{NULL}, an empty string, or
2209 contains no '/' characters, then "." is returned.  The prototype for this
2210 function can be found in @file{libgen.h}.
2211 @end deftypefun
2213 @node strfry
2214 @section strfry
2216 The function below addresses the perennial programming quandary: ``How do
2217 I take good data in string form and painlessly turn it into garbage?''
2218 This is actually a fairly simple task for C programmers who do not use
2219 the GNU C library string functions, but for programs based on the GNU C
2220 library, the @code{strfry} function is the preferred method for
2221 destroying string data.
2223 The prototype for this function is in @file{string.h}.
2225 @comment string.h
2226 @comment GNU
2227 @deftypefun {char *} strfry (char *@var{string})
2229 @code{strfry} creates a pseudorandom anagram of a string, replacing the
2230 input with the anagram in place.  For each position in the string,
2231 @code{strfry} swaps it with a position in the string selected at random
2232 (from a uniform distribution).  The two positions may be the same.
2234 The return value of @code{strfry} is always @var{string}.
2236 @strong{Portability Note:}  This function is unique to the GNU C library.
2238 @end deftypefun
2241 @node Trivial Encryption
2242 @section Trivial Encryption
2243 @cindex encryption
2246 The @code{memfrob} function converts an array of data to something
2247 unrecognizable and back again.  It is not encryption in its usual sense
2248 since it is easy for someone to convert the encrypted data back to clear
2249 text.  The transformation is analogous to Usenet's ``Rot13'' encryption
2250 method for obscuring offensive jokes from sensitive eyes and such.
2251 Unlike Rot13, @code{memfrob} works on arbitrary binary data, not just
2252 text.
2253 @cindex Rot13
2255 For true encryption, @xref{Cryptographic Functions}.
2257 This function is declared in @file{string.h}.
2258 @pindex string.h
2260 @comment string.h
2261 @comment GNU
2262 @deftypefun {void *} memfrob (void *@var{mem}, size_t @var{length})
2264 @code{memfrob} transforms (frobnicates) each byte of the data structure
2265 at @var{mem}, which is @var{length} bytes long, by bitwise exclusive
2266 oring it with binary 00101010.  It does the transformation in place and
2267 its return value is always @var{mem}.
2269 Note that @code{memfrob} a second time on the same data structure
2270 returns it to its original state.
2272 This is a good function for hiding information from someone who doesn't
2273 want to see it or doesn't want to see it very much.  To really prevent
2274 people from retrieving the information, use stronger encryption such as
2275 that described in @xref{Cryptographic Functions}.
2277 @strong{Portability Note:}  This function is unique to the GNU C library.
2279 @end deftypefun
2281 @node Encode Binary Data
2282 @section Encode Binary Data
2284 To store or transfer binary data in environments which only support text
2285 one has to encode the binary data by mapping the input bytes to
2286 characters in the range allowed for storing or transfering.  SVID
2287 systems (and nowadays XPG compliant systems) provide minimal support for
2288 this task.
2290 @comment stdlib.h
2291 @comment XPG
2292 @deftypefun {char *} l64a (long int @var{n})
2293 This function encodes a 32-bit input value using characters from the
2294 basic character set.  It returns a pointer to a 7 character buffer which
2295 contains an encoded version of @var{n}.  To encode a series of bytes the
2296 user must copy the returned string to a destination buffer.  It returns
2297 the empty string if @var{n} is zero, which is somewhat bizarre but
2298 mandated by the standard.@*
2299 @strong{Warning:} Since a static buffer is used this function should not
2300 be used in multi-threaded programs.  There is no thread-safe alternative
2301 to this function in the C library.@*
2302 @strong{Compatibility Note:} The XPG standard states that the return
2303 value of @code{l64a} is undefined if @var{n} is negative.  In the GNU
2304 implementation, @code{l64a} treats its argument as unsigned, so it will
2305 return a sensible encoding for any nonzero @var{n}; however, portable
2306 programs should not rely on this.
2308 To encode a large buffer @code{l64a} must be called in a loop, once for
2309 each 32-bit word of the buffer.  For example, one could do something
2310 like this:
2312 @smallexample
2313 char *
2314 encode (const void *buf, size_t len)
2316   /* @r{We know in advance how long the buffer has to be.} */
2317   unsigned char *in = (unsigned char *) buf;
2318   char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
2319   char *cp = out, *p;
2321   /* @r{Encode the length.} */
2322   /* @r{Using `htonl' is necessary so that the data can be}
2323      @r{decoded even on machines with different byte order.}
2324      @r{`l64a' can return a string shorter than 6 bytes, so }
2325      @r{we pad it with encoding of 0 (}'.'@r{) at the end by }
2326      @r{hand.} */
2328   p = stpcpy (cp, l64a (htonl (len)));
2329   cp = mempcpy (p, "......", 6 - (p - cp));
2331   while (len > 3)
2332     @{
2333       unsigned long int n = *in++;
2334       n = (n << 8) | *in++;
2335       n = (n << 8) | *in++;
2336       n = (n << 8) | *in++;
2337       len -= 4;
2338       p = stpcpy (cp, l64a (htonl (n)));
2339       cp = mempcpy (p, "......", 6 - (p - cp));
2340     @}
2341   if (len > 0)
2342     @{
2343       unsigned long int n = *in++;
2344       if (--len > 0)
2345         @{
2346           n = (n << 8) | *in++;
2347           if (--len > 0)
2348             n = (n << 8) | *in;
2349         @}
2350       cp = stpcpy (cp, l64a (htonl (n)));
2351     @}
2352   *cp = '\0';
2353   return out;
2355 @end smallexample
2357 It is strange that the library does not provide the complete
2358 functionality needed but so be it.
2360 @end deftypefun
2362 To decode data produced with @code{l64a} the following function should be
2363 used.
2365 @comment stdlib.h
2366 @comment XPG
2367 @deftypefun {long int} a64l (const char *@var{string})
2368 The parameter @var{string} should contain a string which was produced by
2369 a call to @code{l64a}.  The function processes at least 6 characters of
2370 this string, and decodes the characters it finds according to the table
2371 below.  It stops decoding when it finds a character not in the table,
2372 rather like @code{atoi}; if you have a buffer which has been broken into
2373 lines, you must be careful to skip over the end-of-line characters.
2375 The decoded number is returned as a @code{long int} value.
2376 @end deftypefun
2378 The @code{l64a} and @code{a64l} functions use a base 64 encoding, in
2379 which each character of an encoded string represents six bits of an
2380 input word.  These symbols are used for the base 64 digits:
2382 @multitable {xxxxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx}
2383 @item              @tab 0 @tab 1 @tab 2 @tab 3 @tab 4 @tab 5 @tab 6 @tab 7
2384 @item       0      @tab @code{.} @tab @code{/} @tab @code{0} @tab @code{1}
2385                    @tab @code{2} @tab @code{3} @tab @code{4} @tab @code{5}
2386 @item       8      @tab @code{6} @tab @code{7} @tab @code{8} @tab @code{9}
2387                    @tab @code{A} @tab @code{B} @tab @code{C} @tab @code{D}
2388 @item       16     @tab @code{E} @tab @code{F} @tab @code{G} @tab @code{H}
2389                    @tab @code{I} @tab @code{J} @tab @code{K} @tab @code{L}
2390 @item       24     @tab @code{M} @tab @code{N} @tab @code{O} @tab @code{P}
2391                    @tab @code{Q} @tab @code{R} @tab @code{S} @tab @code{T}
2392 @item       32     @tab @code{U} @tab @code{V} @tab @code{W} @tab @code{X}
2393                    @tab @code{Y} @tab @code{Z} @tab @code{a} @tab @code{b}
2394 @item       40     @tab @code{c} @tab @code{d} @tab @code{e} @tab @code{f}
2395                    @tab @code{g} @tab @code{h} @tab @code{i} @tab @code{j}
2396 @item       48     @tab @code{k} @tab @code{l} @tab @code{m} @tab @code{n}
2397                    @tab @code{o} @tab @code{p} @tab @code{q} @tab @code{r}
2398 @item       56     @tab @code{s} @tab @code{t} @tab @code{u} @tab @code{v}
2399                    @tab @code{w} @tab @code{x} @tab @code{y} @tab @code{z}
2400 @end multitable
2402 This encoding scheme is not standard.  There are some other encoding
2403 methods which are much more widely used (UU encoding, MIME encoding).
2404 Generally, it is better to use one of these encodings.
2406 @node Argz and Envz Vectors
2407 @section Argz and Envz Vectors
2409 @cindex argz vectors (string vectors)
2410 @cindex string vectors, null-character separated
2411 @cindex argument vectors, null-character separated
2412 @dfn{argz vectors} are vectors of strings in a contiguous block of
2413 memory, each element separated from its neighbors by null-characters
2414 (@code{'\0'}).
2416 @cindex envz vectors (environment vectors)
2417 @cindex environment vectors, null-character separated
2418 @dfn{Envz vectors} are an extension of argz vectors where each element is a
2419 name-value pair, separated by a @code{'='} character (as in a Unix
2420 environment).
2422 @menu
2423 * Argz Functions::              Operations on argz vectors.
2424 * Envz Functions::              Additional operations on environment vectors.
2425 @end menu
2427 @node Argz Functions, Envz Functions, , Argz and Envz Vectors
2428 @subsection Argz Functions
2430 Each argz vector is represented by a pointer to the first element, of
2431 type @code{char *}, and a size, of type @code{size_t}, both of which can
2432 be initialized to @code{0} to represent an empty argz vector.  All argz
2433 functions accept either a pointer and a size argument, or pointers to
2434 them, if they will be modified.
2436 The argz functions use @code{malloc}/@code{realloc} to allocate/grow
2437 argz vectors, and so any argz vector creating using these functions may
2438 be freed by using @code{free}; conversely, any argz function that may
2439 grow a string expects that string to have been allocated using
2440 @code{malloc} (those argz functions that only examine their arguments or
2441 modify them in place will work on any sort of memory).
2442 @xref{Unconstrained Allocation}.
2444 All argz functions that do memory allocation have a return type of
2445 @code{error_t}, and return @code{0} for success, and @code{ENOMEM} if an
2446 allocation error occurs.
2448 @pindex argz.h
2449 These functions are declared in the standard include file @file{argz.h}.
2451 @comment argz.h
2452 @comment GNU
2453 @deftypefun {error_t} argz_create (char *const @var{argv}[], char **@var{argz}, size_t *@var{argz_len})
2454 The @code{argz_create} function converts the Unix-style argument vector
2455 @var{argv} (a vector of pointers to normal C strings, terminated by
2456 @code{(char *)0}; @pxref{Program Arguments}) into an argz vector with
2457 the same elements, which is returned in @var{argz} and @var{argz_len}.
2458 @end deftypefun
2460 @comment argz.h
2461 @comment GNU
2462 @deftypefun {error_t} argz_create_sep (const char *@var{string}, int @var{sep}, char **@var{argz}, size_t *@var{argz_len})
2463 The @code{argz_create_sep} function converts the null-terminated string
2464 @var{string} into an argz vector (returned in @var{argz} and
2465 @var{argz_len}) by splitting it into elements at every occurrence of the
2466 character @var{sep}.
2467 @end deftypefun
2469 @comment argz.h
2470 @comment GNU
2471 @deftypefun {size_t} argz_count (const char *@var{argz}, size_t @var{arg_len})
2472 Returns the number of elements in the argz vector @var{argz} and
2473 @var{argz_len}.
2474 @end deftypefun
2476 @comment argz.h
2477 @comment GNU
2478 @deftypefun {void} argz_extract (char *@var{argz}, size_t @var{argz_len}, char **@var{argv})
2479 The @code{argz_extract} function converts the argz vector @var{argz} and
2480 @var{argz_len} into a Unix-style argument vector stored in @var{argv},
2481 by putting pointers to every element in @var{argz} into successive
2482 positions in @var{argv}, followed by a terminator of @code{0}.
2483 @var{Argv} must be pre-allocated with enough space to hold all the
2484 elements in @var{argz} plus the terminating @code{(char *)0}
2485 (@code{(argz_count (@var{argz}, @var{argz_len}) + 1) * sizeof (char *)}
2486 bytes should be enough).  Note that the string pointers stored into
2487 @var{argv} point into @var{argz}---they are not copies---and so
2488 @var{argz} must be copied if it will be changed while @var{argv} is
2489 still active.  This function is useful for passing the elements in
2490 @var{argz} to an exec function (@pxref{Executing a File}).
2491 @end deftypefun
2493 @comment argz.h
2494 @comment GNU
2495 @deftypefun {void} argz_stringify (char *@var{argz}, size_t @var{len}, int @var{sep})
2496 The @code{argz_stringify} converts @var{argz} into a normal string with
2497 the elements separated by the character @var{sep}, by replacing each
2498 @code{'\0'} inside @var{argz} (except the last one, which terminates the
2499 string) with @var{sep}.  This is handy for printing @var{argz} in a
2500 readable manner.
2501 @end deftypefun
2503 @comment argz.h
2504 @comment GNU
2505 @deftypefun {error_t} argz_add (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str})
2506 The @code{argz_add} function adds the string @var{str} to the end of the
2507 argz vector @code{*@var{argz}}, and updates @code{*@var{argz}} and
2508 @code{*@var{argz_len}} accordingly.
2509 @end deftypefun
2511 @comment argz.h
2512 @comment GNU
2513 @deftypefun {error_t} argz_add_sep (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str}, int @var{delim})
2514 The @code{argz_add_sep} function is similar to @code{argz_add}, but
2515 @var{str} is split into separate elements in the result at occurrences of
2516 the character @var{delim}.  This is useful, for instance, for
2517 adding the components of a Unix search path to an argz vector, by using
2518 a value of @code{':'} for @var{delim}.
2519 @end deftypefun
2521 @comment argz.h
2522 @comment GNU
2523 @deftypefun {error_t} argz_append (char **@var{argz}, size_t *@var{argz_len}, const char *@var{buf}, size_t @var{buf_len})
2524 The @code{argz_append} function appends @var{buf_len} bytes starting at
2525 @var{buf} to the argz vector @code{*@var{argz}}, reallocating
2526 @code{*@var{argz}} to accommodate it, and adding @var{buf_len} to
2527 @code{*@var{argz_len}}.
2528 @end deftypefun
2530 @comment argz.h
2531 @comment GNU
2532 @deftypefun {void} argz_delete (char **@var{argz}, size_t *@var{argz_len}, char *@var{entry})
2533 If @var{entry} points to the beginning of one of the elements in the
2534 argz vector @code{*@var{argz}}, the @code{argz_delete} function will
2535 remove this entry and reallocate @code{*@var{argz}}, modifying
2536 @code{*@var{argz}} and @code{*@var{argz_len}} accordingly.  Note that as
2537 destructive argz functions usually reallocate their argz argument,
2538 pointers into argz vectors such as @var{entry} will then become invalid.
2539 @end deftypefun
2541 @comment argz.h
2542 @comment GNU
2543 @deftypefun {error_t} argz_insert (char **@var{argz}, size_t *@var{argz_len}, char *@var{before}, const char *@var{entry})
2544 The @code{argz_insert} function inserts the string @var{entry} into the
2545 argz vector @code{*@var{argz}} at a point just before the existing
2546 element pointed to by @var{before}, reallocating @code{*@var{argz}} and
2547 updating @code{*@var{argz}} and @code{*@var{argz_len}}.  If @var{before}
2548 is @code{0}, @var{entry} is added to the end instead (as if by
2549 @code{argz_add}).  Since the first element is in fact the same as
2550 @code{*@var{argz}}, passing in @code{*@var{argz}} as the value of
2551 @var{before} will result in @var{entry} being inserted at the beginning.
2552 @end deftypefun
2554 @comment argz.h
2555 @comment GNU
2556 @deftypefun {char *} argz_next (char *@var{argz}, size_t @var{argz_len}, const char *@var{entry})
2557 The @code{argz_next} function provides a convenient way of iterating
2558 over the elements in the argz vector @var{argz}.  It returns a pointer
2559 to the next element in @var{argz} after the element @var{entry}, or
2560 @code{0} if there are no elements following @var{entry}.  If @var{entry}
2561 is @code{0}, the first element of @var{argz} is returned.
2563 This behavior suggests two styles of iteration:
2565 @smallexample
2566     char *entry = 0;
2567     while ((entry = argz_next (@var{argz}, @var{argz_len}, entry)))
2568       @var{action};
2569 @end smallexample
2571 (the double parentheses are necessary to make some C compilers shut up
2572 about what they consider a questionable @code{while}-test) and:
2574 @smallexample
2575     char *entry;
2576     for (entry = @var{argz};
2577          entry;
2578          entry = argz_next (@var{argz}, @var{argz_len}, entry))
2579       @var{action};
2580 @end smallexample
2582 Note that the latter depends on @var{argz} having a value of @code{0} if
2583 it is empty (rather than a pointer to an empty block of memory); this
2584 invariant is maintained for argz vectors created by the functions here.
2585 @end deftypefun
2587 @comment argz.h
2588 @comment GNU
2589 @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}})
2590 Replace any occurrences of the string @var{str} in @var{argz} with
2591 @var{with}, reallocating @var{argz} as necessary.  If
2592 @var{replace_count} is non-zero, @code{*@var{replace_count}} will be
2593 incremented by number of replacements performed.
2594 @end deftypefun
2596 @node Envz Functions, , Argz Functions, Argz and Envz Vectors
2597 @subsection Envz Functions
2599 Envz vectors are just argz vectors with additional constraints on the form
2600 of each element; as such, argz functions can also be used on them, where it
2601 makes sense.
2603 Each element in an envz vector is a name-value pair, separated by a @code{'='}
2604 character; if multiple @code{'='} characters are present in an element, those
2605 after the first are considered part of the value, and treated like all other
2606 non-@code{'\0'} characters.
2608 If @emph{no} @code{'='} characters are present in an element, that element is
2609 considered the name of a ``null'' entry, as distinct from an entry with an
2610 empty value: @code{envz_get} will return @code{0} if given the name of null
2611 entry, whereas an entry with an empty value would result in a value of
2612 @code{""}; @code{envz_entry} will still find such entries, however.  Null
2613 entries can be removed with @code{envz_strip} function.
2615 As with argz functions, envz functions that may allocate memory (and thus
2616 fail) have a return type of @code{error_t}, and return either @code{0} or
2617 @code{ENOMEM}.
2619 @pindex envz.h
2620 These functions are declared in the standard include file @file{envz.h}.
2622 @comment envz.h
2623 @comment GNU
2624 @deftypefun {char *} envz_entry (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
2625 The @code{envz_entry} function finds the entry in @var{envz} with the name
2626 @var{name}, and returns a pointer to the whole entry---that is, the argz
2627 element which begins with @var{name} followed by a @code{'='} character.  If
2628 there is no entry with that name, @code{0} is returned.
2629 @end deftypefun
2631 @comment envz.h
2632 @comment GNU
2633 @deftypefun {char *} envz_get (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
2634 The @code{envz_get} function finds the entry in @var{envz} with the name
2635 @var{name} (like @code{envz_entry}), and returns a pointer to the value
2636 portion of that entry (following the @code{'='}).  If there is no entry with
2637 that name (or only a null entry), @code{0} is returned.
2638 @end deftypefun
2640 @comment envz.h
2641 @comment GNU
2642 @deftypefun {error_t} envz_add (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name}, const char *@var{value})
2643 The @code{envz_add} function adds an entry to @code{*@var{envz}}
2644 (updating @code{*@var{envz}} and @code{*@var{envz_len}}) with the name
2645 @var{name}, and value @var{value}.  If an entry with the same name
2646 already exists in @var{envz}, it is removed first.  If @var{value} is
2647 @code{0}, then the new entry will the special null type of entry
2648 (mentioned above).
2649 @end deftypefun
2651 @comment envz.h
2652 @comment GNU
2653 @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})
2654 The @code{envz_merge} function adds each entry in @var{envz2} to @var{envz},
2655 as if with @code{envz_add}, updating @code{*@var{envz}} and
2656 @code{*@var{envz_len}}.  If @var{override} is true, then values in @var{envz2}
2657 will supersede those with the same name in @var{envz}, otherwise not.
2659 Null entries are treated just like other entries in this respect, so a null
2660 entry in @var{envz} can prevent an entry of the same name in @var{envz2} from
2661 being added to @var{envz}, if @var{override} is false.
2662 @end deftypefun
2664 @comment envz.h
2665 @comment GNU
2666 @deftypefun {void} envz_strip (char **@var{envz}, size_t *@var{envz_len})
2667 The @code{envz_strip} function removes any null entries from @var{envz},
2668 updating @code{*@var{envz}} and @code{*@var{envz_len}}.
2669 @end deftypefun