(Search Functions): Fix typo.
[platform/upstream/glibc.git] / manual / string.texi
1 @node String and Array Utilities, Character Set Handling, Character Handling, Top
2 @c %MENU% Utilities for copying and comparing strings and arrays
3 @chapter String and Array Utilities
4
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.
11
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.
16
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.
22
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
41
42 @node Representation of Strings
43 @section Representation of Strings
44 @cindex string, representation of
45
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.
50
51 @cindex string
52 @cindex null character
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.
62
63 By convention, a @dfn{null character}, @code{'\0'}, marks the end of a
64 string.  For example, in testing to see whether the @code{char *}
65 variable @var{p} points to a null character marking the end of a string,
66 you can write @code{!*@var{p}} or @code{*@var{p} == '\0'}.
67
68 A null character is quite different conceptually from a null pointer,
69 although both are represented by the integer @code{0}.
70
71 @cindex string literal
72 @dfn{String literals} appear in C program source as strings of
73 characters between double-quote characters (@samp{"}).  In @w{ISO C},
74 string literals can also be formed by @dfn{string concatenation}:
75 @code{"a" "b"} is the same as @code{"ab"}.  Modification of string
76 literals is not allowed by the GNU C compiler, because literals
77 are placed in read-only storage.
78
79 Character arrays that are declared @code{const} cannot be modified
80 either.  It's generally good style to declare non-modifiable string
81 pointers to be of type @code{const char *}, since this often allows the
82 C compiler to detect accidental modifications as well as providing some
83 amount of documentation about what your program intends to do with the
84 string.
85
86 The amount of memory allocated for the character array may extend past
87 the null character that normally marks the end of the string.  In this
88 document, the term @dfn{allocated size} is always used to refer to the
89 total amount of memory allocated for the string, while the term
90 @dfn{length} refers to the number of characters up to (but not
91 including) the terminating null character.
92 @cindex length of string
93 @cindex allocation size of string
94 @cindex size of string
95 @cindex string length
96 @cindex string allocation
97
98 A notorious source of program bugs is trying to put more characters in a
99 string than fit in its allocated size.  When writing code that extends
100 strings or moves characters into a pre-allocated array, you should be
101 very careful to keep track of the length of the text and make explicit
102 checks for overflowing the array.  Many of the library functions
103 @emph{do not} do this for you!  Remember also that you need to allocate
104 an extra byte to hold the null character that marks the end of the
105 string.
106
107 @node String/Array Conventions
108 @section String and Array Conventions
109
110 This chapter describes both functions that work on arbitrary arrays or
111 blocks of memory, and functions that are specific to null-terminated
112 arrays of characters.
113
114 Functions that operate on arbitrary blocks of memory have names
115 beginning with @samp{mem} (such as @code{memcpy}) and invariably take an
116 argument which specifies the size (in bytes) of the block of memory to
117 operate on.  The array arguments and return values for these functions
118 have type @code{void *}, and as a matter of style, the elements of these
119 arrays are referred to as ``bytes''.  You can pass any kind of pointer
120 to these functions, and the @code{sizeof} operator is useful in
121 computing the value for the size argument.
122
123 In contrast, functions that operate specifically on strings have names
124 beginning with @samp{str} (such as @code{strcpy}) and look for a null
125 character to terminate the string instead of requiring an explicit size
126 argument to be passed.  (Some of these functions accept a specified
127 maximum length, but they also check for premature termination with a
128 null character.)  The array arguments and return values for these
129 functions have type @code{char *}, and the array elements are referred
130 to as ``characters''.
131
132 In many cases, there are both @samp{mem} and @samp{str} versions of a
133 function.  The one that is more appropriate to use depends on the exact
134 situation.  When your program is manipulating arbitrary arrays or blocks of
135 storage, then you should always use the @samp{mem} functions.  On the
136 other hand, when you are manipulating null-terminated strings it is
137 usually more convenient to use the @samp{str} functions, unless you
138 already know the length of the string in advance.
139
140 @node String Length
141 @section String Length
142
143 You can get the length of a string using the @code{strlen} function.
144 This function is declared in the header file @file{string.h}.
145 @pindex string.h
146
147 @comment string.h
148 @comment ISO
149 @deftypefun size_t strlen (const char *@var{s})
150 The @code{strlen} function returns the length of the null-terminated
151 string @var{s}.  (In other words, it returns the offset of the terminating
152 null character within the array.)
153
154 For example,
155 @smallexample
156 strlen ("hello, world")
157     @result{} 12
158 @end smallexample
159
160 When applied to a character array, the @code{strlen} function returns
161 the length of the string stored there, not its allocated size.  You can
162 get the allocated size of the character array that holds a string using
163 the @code{sizeof} operator:
164
165 @smallexample
166 char string[32] = "hello, world";
167 sizeof (string)
168     @result{} 32
169 strlen (string)
170     @result{} 12
171 @end smallexample
172
173 But beware, this will not work unless @var{string} is the character
174 array itself, not a pointer to it.  For example:
175
176 @smallexample
177 char string[32] = "hello, world";
178 char *ptr = string;
179 sizeof (string)
180     @result{} 32
181 sizeof (ptr)
182     @result{} 4  /* @r{(on a machine with 4 byte pointers)} */
183 @end smallexample
184
185 This is an easy mistake to make when you are working with functions that
186 take string arguments; those arguments are always pointers, not arrays.
187
188 @end deftypefun
189
190 @comment string.h
191 @comment GNU
192 @deftypefun size_t strnlen (const char *@var{s}, size_t @var{maxlen})
193 The @code{strnlen} function returns the length of the null-terminated
194 string @var{s} is this length is smaller than @var{maxlen}.  Otherwise
195 it returns @var{maxlen}.  Therefore this function is equivalent to
196 @code{(strlen (@var{s}) < n ? strlen (@var{s}) : @var{maxlen})} but it
197 is more efficient.
198
199 @smallexample
200 char string[32] = "hello, world";
201 strnlen (string, 32)
202     @result{} 12
203 strnlen (string, 5)
204     @result{} 5
205 @end smallexample
206
207 This function is a GNU extension.
208 @end deftypefun
209
210 @node Copying and Concatenation
211 @section Copying and Concatenation
212
213 You can use the functions described in this section to copy the contents
214 of strings and arrays, or to append the contents of one string to
215 another.  These functions are declared in the header file
216 @file{string.h}.
217 @pindex string.h
218 @cindex copying strings and arrays
219 @cindex string copy functions
220 @cindex array copy functions
221 @cindex concatenating strings
222 @cindex string concatenation functions
223
224 A helpful way to remember the ordering of the arguments to the functions
225 in this section is that it corresponds to an assignment expression, with
226 the destination array specified to the left of the source array.  All
227 of these functions return the address of the destination array.
228
229 Most of these functions do not work properly if the source and
230 destination arrays overlap.  For example, if the beginning of the
231 destination array overlaps the end of the source array, the original
232 contents of that part of the source array may get overwritten before it
233 is copied.  Even worse, in the case of the string functions, the null
234 character marking the end of the string may be lost, and the copy
235 function might get stuck in a loop trashing all the memory allocated to
236 your program.
237
238 All functions that have problems copying between overlapping arrays are
239 explicitly identified in this manual.  In addition to functions in this
240 section, there are a few others like @code{sprintf} (@pxref{Formatted
241 Output Functions}) and @code{scanf} (@pxref{Formatted Input
242 Functions}).
243
244 @comment string.h
245 @comment ISO
246 @deftypefun {void *} memcpy (void *@var{to}, const void *@var{from}, size_t @var{size})
247 The @code{memcpy} function copies @var{size} bytes from the object
248 beginning at @var{from} into the object beginning at @var{to}.  The
249 behavior of this function is undefined if the two arrays @var{to} and
250 @var{from} overlap; use @code{memmove} instead if overlapping is possible.
251
252 The value returned by @code{memcpy} is the value of @var{to}.
253
254 Here is an example of how you might use @code{memcpy} to copy the
255 contents of an array:
256
257 @smallexample
258 struct foo *oldarray, *newarray;
259 int arraysize;
260 @dots{}
261 memcpy (new, old, arraysize * sizeof (struct foo));
262 @end smallexample
263 @end deftypefun
264
265 @comment string.h
266 @comment GNU
267 @deftypefun {void *} mempcpy (void *@var{to}, const void *@var{from}, size_t @var{size})
268 The @code{mempcpy} function is nearly identical to the @code{memcpy}
269 function.  It copies @var{size} bytes from the object beginning at
270 @code{from} into the object pointed to by @var{to}.  But instead of
271 returning the value of @var{to} it returns a pointer to the byte
272 following the last written byte in the object beginning at @var{to}.
273 I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
274
275 This function is useful in situations where a number of objects shall be
276 copied to consecutive memory positions.
277
278 @smallexample
279 void *
280 combine (void *o1, size_t s1, void *o2, size_t s2)
281 @{
282   void *result = malloc (s1 + s2);
283   if (result != NULL)
284     mempcpy (mempcpy (result, o1, s1), o2, s2);
285   return result;
286 @}
287 @end smallexample
288
289 This function is a GNU extension.
290 @end deftypefun
291
292 @comment string.h
293 @comment ISO
294 @deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
295 @code{memmove} copies the @var{size} bytes at @var{from} into the
296 @var{size} bytes at @var{to}, even if those two blocks of space
297 overlap.  In the case of overlap, @code{memmove} is careful to copy the
298 original values of the bytes in the block at @var{from}, including those
299 bytes which also belong to the block at @var{to}.
300 @end deftypefun
301
302 @comment string.h
303 @comment SVID
304 @deftypefun {void *} memccpy (void *@var{to}, const void *@var{from}, int @var{c}, size_t @var{size})
305 This function copies no more than @var{size} bytes from @var{from} to
306 @var{to}, stopping if a byte matching @var{c} is found.  The return
307 value is a pointer into @var{to} one byte past where @var{c} was copied,
308 or a null pointer if no byte matching @var{c} appeared in the first
309 @var{size} bytes of @var{from}.
310 @end deftypefun
311
312 @comment string.h
313 @comment ISO
314 @deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
315 This function copies the value of @var{c} (converted to an
316 @code{unsigned char}) into each of the first @var{size} bytes of the
317 object beginning at @var{block}.  It returns the value of @var{block}.
318 @end deftypefun
319
320 @comment string.h
321 @comment ISO
322 @deftypefun {char *} strcpy (char *@var{to}, const char *@var{from})
323 This copies characters from the string @var{from} (up to and including
324 the terminating null character) into the string @var{to}.  Like
325 @code{memcpy}, this function has undefined results if the strings
326 overlap.  The return value is the value of @var{to}.
327 @end deftypefun
328
329 @comment string.h
330 @comment ISO
331 @deftypefun {char *} strncpy (char *@var{to}, const char *@var{from}, size_t @var{size})
332 This function is similar to @code{strcpy} but always copies exactly
333 @var{size} characters into @var{to}.
334
335 If the length of @var{from} is more than @var{size}, then @code{strncpy}
336 copies just the first @var{size} characters.  Note that in this case
337 there is no null terminator written into @var{to}.
338
339 If the length of @var{from} is less than @var{size}, then @code{strncpy}
340 copies all of @var{from}, followed by enough null characters to add up
341 to @var{size} characters in all.  This behavior is rarely useful, but it
342 is specified by the @w{ISO C} standard.
343
344 The behavior of @code{strncpy} is undefined if the strings overlap.
345
346 Using @code{strncpy} as opposed to @code{strcpy} is a way to avoid bugs
347 relating to writing past the end of the allocated space for @var{to}.
348 However, it can also make your program much slower in one common case:
349 copying a string which is probably small into a potentially large buffer.
350 In this case, @var{size} may be large, and when it is, @code{strncpy} will
351 waste a considerable amount of time copying null characters.
352 @end deftypefun
353
354 @comment string.h
355 @comment SVID
356 @deftypefun {char *} strdup (const char *@var{s})
357 This function copies the null-terminated string @var{s} into a newly
358 allocated string.  The string is allocated using @code{malloc}; see
359 @ref{Unconstrained Allocation}.  If @code{malloc} cannot allocate space
360 for the new string, @code{strdup} returns a null pointer.  Otherwise it
361 returns a pointer to the new string.
362 @end deftypefun
363
364 @comment string.h
365 @comment GNU
366 @deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
367 This function is similar to @code{strdup} but always copies at most
368 @var{size} characters into the newly allocated string.
369
370 If the length of @var{s} is more than @var{size}, then @code{strndup}
371 copies just the first @var{size} characters and adds a closing null
372 terminator.  Otherwise all characters are copied and the string is
373 terminated.
374
375 This function is different to @code{strncpy} in that it always
376 terminates the destination string.
377
378 @code{strndup} is a GNU extension.
379 @end deftypefun
380
381 @comment string.h
382 @comment Unknown origin
383 @deftypefun {char *} stpcpy (char *@var{to}, const char *@var{from})
384 This function is like @code{strcpy}, except that it returns a pointer to
385 the end of the string @var{to} (that is, the address of the terminating
386 null character) rather than the beginning.
387
388 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
389 and @samp{bar} to produce @samp{foobar}, which it then prints.
390
391 @smallexample
392 @include stpcpy.c.texi
393 @end smallexample
394
395 This function is not part of the ISO or POSIX standards, and is not
396 customary on Unix systems, but we did not invent it either.  Perhaps it
397 comes from MS-DOG.
398
399 Its behavior is undefined if the strings overlap.
400 @end deftypefun
401
402 @comment string.h
403 @comment GNU
404 @deftypefun {char *} stpncpy (char *@var{to}, const char *@var{from}, size_t @var{size})
405 This function is similar to @code{stpcpy} but copies always exactly
406 @var{size} characters into @var{to}.
407
408 If the length of @var{from} is more then @var{size}, then @code{stpncpy}
409 copies just the first @var{size} characters and returns a pointer to the
410 character directly following the one which was copied last.  Note that in
411 this case there is no null terminator written into @var{to}.
412
413 If the length of @var{from} is less than @var{size}, then @code{stpncpy}
414 copies all of @var{from}, followed by enough null characters to add up
415 to @var{size} characters in all.  This behaviour is rarely useful, but it
416 is implemented to be useful in contexts where this behaviour of the
417 @code{strncpy} is used.  @code{stpncpy} returns a pointer to the
418 @emph{first} written null character.
419
420 This function is not part of ISO or POSIX but was found useful while
421 developing the GNU C Library itself.
422
423 Its behaviour is undefined if the strings overlap.
424 @end deftypefun
425
426 @comment string.h
427 @comment GNU
428 @deftypefn {Macro} {char *} strdupa (const char *@var{s})
429 This macro is similar to @code{strdup} but allocates the new string
430 using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
431 Automatic}).  This means of course the returned string has the same
432 limitations as any block of memory allocated using @code{alloca}.
433
434 For obvious reasons @code{strdupa} is implemented only as a macro;
435 you cannot get the address of this function.  Despite this limitation
436 it is a useful function.  The following code shows a situation where
437 using @code{malloc} would be a lot more expensive.
438
439 @smallexample
440 @include strdupa.c.texi
441 @end smallexample
442
443 Please note that calling @code{strtok} using @var{path} directly is
444 invalid.
445
446 This function is only available if GNU CC is used.
447 @end deftypefn
448
449 @comment string.h
450 @comment GNU
451 @deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
452 This function is similar to @code{strndup} but like @code{strdupa} it
453 allocates the new string using @code{alloca}
454 @pxref{Variable Size Automatic}.  The same advantages and limitations
455 of @code{strdupa} are valid for @code{strndupa}, too.
456
457 This function is implemented only as a macro, just like @code{strdupa}.
458
459 @code{strndupa} is only available if GNU CC is used.
460 @end deftypefn
461
462 @comment string.h
463 @comment ISO
464 @deftypefun {char *} strcat (char *@var{to}, const char *@var{from})
465 The @code{strcat} function is similar to @code{strcpy}, except that the
466 characters from @var{from} are concatenated or appended to the end of
467 @var{to}, instead of overwriting it.  That is, the first character from
468 @var{from} overwrites the null character marking the end of @var{to}.
469
470 An equivalent definition for @code{strcat} would be:
471
472 @smallexample
473 char *
474 strcat (char *to, const char *from)
475 @{
476   strcpy (to + strlen (to), from);
477   return to;
478 @}
479 @end smallexample
480
481 This function has undefined results if the strings overlap.
482 @end deftypefun
483
484 Programmers using the @code{strcat} function (or the following
485 @code{strncat} function for that matter) can easily be recognized as
486 lazy.  In almost all situations the lengths of the participating strings
487 are known.  Or at least, one could know them if one keeps track of the
488 results of the various function calls.  But then it is very inefficient
489 to use @code{strcat}.  A lot of time is wasted finding the end of the
490 destination string so that the actual copying can start.  This is a
491 common example:
492
493 @cindex __va_copy
494 @cindex va_copy
495 @smallexample
496 /* @r{This function concatenates arbitrarily many strings.  The last}
497    @r{parameter must be @code{NULL}.}  */
498 char *
499 concat (const char *str, ...)
500 @{
501   va_list ap, ap2;
502   size_t total = 1;
503   const char *s;
504   char *result;
505
506   va_start (ap, str);
507   /* @r{Actually @code{va_copy}, but this is the name more gcc versions}
508      @r{understand.}  */
509   __va_copy (ap2, ap);
510
511   /* @r{Determine how much space we need.}  */
512   for (s = str; s != NULL; s = va_arg (ap, const char *))
513     total += strlen (s);
514
515   va_end (ap);
516
517   result = (char *) malloc (total);
518   if (result != NULL)
519     @{
520       result[0] = '\0';
521
522       /* @r{Copy the strings.}  */
523       for (s = str; s != NULL; s = va_arg (ap2, const char *))
524         strcat (result, s);
525     @}
526
527   va_end (ap2);
528
529   return result;
530 @}
531 @end smallexample
532
533 This looks quite simple, especially the second loop where the strings
534 are actually copied.  But these innocent lines hide a major performance
535 penalty.  Just imagine that ten strings of 100 bytes each have to be
536 concatenated.  For the second string we search the already stored 100
537 bytes for the end of the string so that we can append the next string.
538 For all strings in total the comparisons necessary to find the end of
539 the intermediate results sums up to 5500!  If we combine the copying
540 with the search for the allocation we can write this function more
541 efficient:
542
543 @smallexample
544 char *
545 concat (const char *str, ...)
546 @{
547   va_list ap;
548   size_t allocated = 100;
549   char *result = (char *) malloc (allocated);
550   char *wp;
551
552   if (allocated != NULL)
553     @{
554       char *newp;
555
556       va_start (ap, atr);
557
558       wp = result;
559       for (s = str; s != NULL; s = va_arg (ap, const char *))
560         @{
561           size_t len = strlen (s);
562
563           /* @r{Resize the allocated memory if necessary.}  */
564           if (wp + len + 1 > result + allocated)
565             @{
566               allocated = (allocated + len) * 2;
567               newp = (char *) realloc (result, allocated);
568               if (newp == NULL)
569                 @{
570                   free (result);
571                   return NULL;
572                 @}
573               wp = newp + (wp - result);
574               result = newp;
575             @}
576
577           wp = mempcpy (wp, s, len);
578         @}
579
580       /* @r{Terminate the result string.}  */
581       *wp++ = '\0';
582
583       /* @r{Resize memory to the optimal size.}  */
584       newp = realloc (result, wp - result);
585       if (newp != NULL)
586         result = newp;
587
588       va_end (ap);
589     @}
590
591   return result;
592 @}
593 @end smallexample
594
595 With a bit more knowledge about the input strings one could fine-tune
596 the memory allocation.  The difference we are pointing to here is that
597 we don't use @code{strcat} anymore.  We always keep track of the length
598 of the current intermediate result so we can safe us the search for the
599 end of the string and use @code{mempcpy}.  Please note that we also
600 don't use @code{stpcpy} which might seem more natural since we handle
601 with strings.  But this is not necessary since we already know the
602 length of the string and therefore can use the faster memory copying
603 function.
604
605 Whenever a programmer feels the need to use @code{strcat} she or he
606 should think twice and look through the program whether the code cannot
607 be rewritten to take advantage of already calculated results.  Again: it
608 is almost always unnecessary to use @code{strcat}.
609
610 @comment string.h
611 @comment ISO
612 @deftypefun {char *} strncat (char *@var{to}, const char *@var{from}, size_t @var{size})
613 This function is like @code{strcat} except that not more than @var{size}
614 characters from @var{from} are appended to the end of @var{to}.  A
615 single null character is also always appended to @var{to}, so the total
616 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
617 longer than its initial length.
618
619 The @code{strncat} function could be implemented like this:
620
621 @smallexample
622 @group
623 char *
624 strncat (char *to, const char *from, size_t size)
625 @{
626   strncpy (to + strlen (to), from, size);
627   return to;
628 @}
629 @end group
630 @end smallexample
631
632 The behavior of @code{strncat} is undefined if the strings overlap.
633 @end deftypefun
634
635 Here is an example showing the use of @code{strncpy} and @code{strncat}.
636 Notice how, in the call to @code{strncat}, the @var{size} parameter
637 is computed to avoid overflowing the character array @code{buffer}.
638
639 @smallexample
640 @include strncat.c.texi
641 @end smallexample
642
643 @noindent
644 The output produced by this program looks like:
645
646 @smallexample
647 hello
648 hello, wo
649 @end smallexample
650
651 @comment string.h
652 @comment BSD
653 @deftypefun void bcopy (const void *@var{from}, void *@var{to}, size_t @var{size})
654 This is a partially obsolete alternative for @code{memmove}, derived from
655 BSD.  Note that it is not quite equivalent to @code{memmove}, because the
656 arguments are not in the same order and there is no return value.
657 @end deftypefun
658
659 @comment string.h
660 @comment BSD
661 @deftypefun void bzero (void *@var{block}, size_t @var{size})
662 This is a partially obsolete alternative for @code{memset}, derived from
663 BSD.  Note that it is not as general as @code{memset}, because the only
664 value it can store is zero.
665 @end deftypefun
666
667 @node String/Array Comparison
668 @section String/Array Comparison
669 @cindex comparing strings and arrays
670 @cindex string comparison functions
671 @cindex array comparison functions
672 @cindex predicates on strings
673 @cindex predicates on arrays
674
675 You can use the functions in this section to perform comparisons on the
676 contents of strings and arrays.  As well as checking for equality, these
677 functions can also be used as the ordering functions for sorting
678 operations.  @xref{Searching and Sorting}, for an example of this.
679
680 Unlike most comparison operations in C, the string comparison functions
681 return a nonzero value if the strings are @emph{not} equivalent rather
682 than if they are.  The sign of the value indicates the relative ordering
683 of the first characters in the strings that are not equivalent:  a
684 negative value indicates that the first string is ``less'' than the
685 second, while a positive value indicates that the first string is
686 ``greater''.
687
688 The most common use of these functions is to check only for equality.
689 This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
690
691 All of these functions are declared in the header file @file{string.h}.
692 @pindex string.h
693
694 @comment string.h
695 @comment ISO
696 @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
697 The function @code{memcmp} compares the @var{size} bytes of memory
698 beginning at @var{a1} against the @var{size} bytes of memory beginning
699 at @var{a2}.  The value returned has the same sign as the difference
700 between the first differing pair of bytes (interpreted as @code{unsigned
701 char} objects, then promoted to @code{int}).
702
703 If the contents of the two blocks are equal, @code{memcmp} returns
704 @code{0}.
705 @end deftypefun
706
707 On arbitrary arrays, the @code{memcmp} function is mostly useful for
708 testing equality.  It usually isn't meaningful to do byte-wise ordering
709 comparisons on arrays of things other than bytes.  For example, a
710 byte-wise comparison on the bytes that make up floating-point numbers
711 isn't likely to tell you anything about the relationship between the
712 values of the floating-point numbers.
713
714 You should also be careful about using @code{memcmp} to compare objects
715 that can contain ``holes'', such as the padding inserted into structure
716 objects to enforce alignment requirements, extra space at the end of
717 unions, and extra characters at the ends of strings whose length is less
718 than their allocated size.  The contents of these ``holes'' are
719 indeterminate and may cause strange behavior when performing byte-wise
720 comparisons.  For more predictable results, perform an explicit
721 component-wise comparison.
722
723 For example, given a structure type definition like:
724
725 @smallexample
726 struct foo
727   @{
728     unsigned char tag;
729     union
730       @{
731         double f;
732         long i;
733         char *p;
734       @} value;
735   @};
736 @end smallexample
737
738 @noindent
739 you are better off writing a specialized comparison function to compare
740 @code{struct foo} objects instead of comparing them with @code{memcmp}.
741
742 @comment string.h
743 @comment ISO
744 @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
745 The @code{strcmp} function compares the string @var{s1} against
746 @var{s2}, returning a value that has the same sign as the difference
747 between the first differing pair of characters (interpreted as
748 @code{unsigned char} objects, then promoted to @code{int}).
749
750 If the two strings are equal, @code{strcmp} returns @code{0}.
751
752 A consequence of the ordering used by @code{strcmp} is that if @var{s1}
753 is an initial substring of @var{s2}, then @var{s1} is considered to be
754 ``less than'' @var{s2}.
755 @end deftypefun
756
757 @comment string.h
758 @comment BSD
759 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
760 This function is like @code{strcmp}, except that differences in case are
761 ignored.  How uppercase and lowercase characters are related is
762 determined by the currently selected locale.  In the standard @code{"C"}
763 locale the characters @"A and @"a do not match but in a locale which
764 regards these characters as parts of the alphabet they do match.
765
766 @noindent
767 @code{strcasecmp} is derived from BSD.
768 @end deftypefun
769
770 @comment string.h
771 @comment BSD
772 @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
773 This function is like @code{strncmp}, except that differences in case
774 are ignored.  Like @code{strcasecmp}, it is locale dependent how
775 uppercase and lowercase characters are related.
776
777 @noindent
778 @code{strncasecmp} is a GNU extension.
779 @end deftypefun
780
781 @comment string.h
782 @comment ISO
783 @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
784 This function is the similar to @code{strcmp}, except that no more than
785 @var{size} characters are compared.  In other words, if the two strings are
786 the same in their first @var{size} characters, the return value is zero.
787 @end deftypefun
788
789 Here are some examples showing the use of @code{strcmp} and @code{strncmp}.
790 These examples assume the use of the ASCII character set.  (If some
791 other character set---say, EBCDIC---is used instead, then the glyphs
792 are associated with different numeric codes, and the return values
793 and ordering may differ.)
794
795 @smallexample
796 strcmp ("hello", "hello")
797     @result{} 0    /* @r{These two strings are the same.} */
798 strcmp ("hello", "Hello")
799     @result{} 32   /* @r{Comparisons are case-sensitive.} */
800 strcmp ("hello", "world")
801     @result{} -15  /* @r{The character @code{'h'} comes before @code{'w'}.} */
802 strcmp ("hello", "hello, world")
803     @result{} -44  /* @r{Comparing a null character against a comma.} */
804 strncmp ("hello", "hello, world", 5)
805     @result{} 0    /* @r{The initial 5 characters are the same.} */
806 strncmp ("hello, world", "hello, stupid world!!!", 5)
807     @result{} 0    /* @r{The initial 5 characters are the same.} */
808 @end smallexample
809
810 @comment string.h
811 @comment GNU
812 @deftypefun int strverscmp (const char *@var{s1}, const char *@var{s2})
813 The @code{strverscmp} function compares the string @var{s1} against
814 @var{s2}, considering them as holding indices/version numbers.  Return
815 value follows the same conventions as found in the @code{strverscmp}
816 function.  In fact, if @var{s1} and @var{s2} contain no digits,
817 @code{strverscmp} behaves like @code{strcmp}.
818
819 Basically, we compare strings normally (character by character), until
820 we find a digit in each string - then we enter a special comparison
821 mode, where each sequence of digits is taken as a whole.  If we reach the
822 end of these two parts without noticing a difference, we return to the
823 standard comparison mode.  There are two types of numeric parts:
824 "integral" and "fractional" (those  begin with a '0'). The types
825 of the numeric parts affect the way we sort them:
826
827 @itemize @bullet
828 @item
829 integral/integral: we compare values as you would expect.
830
831 @item
832 fractional/integral: the fractional part is less than the integral one.
833 Again, no surprise.
834
835 @item
836 fractional/fractional: the things become a bit more complex.
837 If the common prefix contains only leading zeroes, the longest part is less
838 than the other one; else the comparison behaves normally.
839 @end itemize
840
841 @smallexample
842 strverscmp ("no digit", "no digit")
843     @result{} 0    /* @r{same behaviour as strcmp.} */
844 strverscmp ("item#99", "item#100")
845     @result{} <0   /* @r{same prefix, but 99 < 100.} */
846 strverscmp ("alpha1", "alpha001")
847     @result{} >0   /* @r{fractional part inferior to integral one.} */
848 strverscmp ("part1_f012", "part1_f01")
849     @result{} >0   /* @r{two fractional parts.} */
850 strverscmp ("foo.009", "foo.0")
851     @result{} <0   /* @r{idem, but with leading zeroes only.} */
852 @end smallexample
853
854 This function is especially useful when dealing with filename sorting,
855 because filenames frequently hold indices/version numbers.
856
857 @code{strverscmp} is a GNU extension.
858 @end deftypefun
859
860 @comment string.h
861 @comment BSD
862 @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
863 This is an obsolete alias for @code{memcmp}, derived from BSD.
864 @end deftypefun
865
866 @node Collation Functions
867 @section Collation Functions
868
869 @cindex collating strings
870 @cindex string collation functions
871
872 In some locales, the conventions for lexicographic ordering differ from
873 the strict numeric ordering of character codes.  For example, in Spanish
874 most glyphs with diacritical marks such as accents are not considered
875 distinct letters for the purposes of collation.  On the other hand, the
876 two-character sequence @samp{ll} is treated as a single letter that is
877 collated immediately after @samp{l}.
878
879 You can use the functions @code{strcoll} and @code{strxfrm} (declared in
880 the header file @file{string.h}) to compare strings using a collation
881 ordering appropriate for the current locale.  The locale used by these
882 functions in particular can be specified by setting the locale for the
883 @code{LC_COLLATE} category; see @ref{Locales}.
884 @pindex string.h
885
886 In the standard C locale, the collation sequence for @code{strcoll} is
887 the same as that for @code{strcmp}.
888
889 Effectively, the way these functions work is by applying a mapping to
890 transform the characters in a string to a byte sequence that represents
891 the string's position in the collating sequence of the current locale.
892 Comparing two such byte sequences in a simple fashion is equivalent to
893 comparing the strings with the locale's collating sequence.
894
895 The function @code{strcoll} performs this translation implicitly, in
896 order to do one comparison.  By contrast, @code{strxfrm} performs the
897 mapping explicitly.  If you are making multiple comparisons using the
898 same string or set of strings, it is likely to be more efficient to use
899 @code{strxfrm} to transform all the strings just once, and subsequently
900 compare the transformed strings with @code{strcmp}.
901
902 @comment string.h
903 @comment ISO
904 @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
905 The @code{strcoll} function is similar to @code{strcmp} but uses the
906 collating sequence of the current locale for collation (the
907 @code{LC_COLLATE} locale).
908 @end deftypefun
909
910 Here is an example of sorting an array of strings, using @code{strcoll}
911 to compare them.  The actual sort algorithm is not written here; it
912 comes from @code{qsort} (@pxref{Array Sort Function}).  The job of the
913 code shown here is to say how to compare the strings while sorting them.
914 (Later on in this section, we will show a way to do this more
915 efficiently using @code{strxfrm}.)
916
917 @smallexample
918 /* @r{This is the comparison function used with @code{qsort}.} */
919
920 int
921 compare_elements (char **p1, char **p2)
922 @{
923   return strcoll (*p1, *p2);
924 @}
925
926 /* @r{This is the entry point---the function to sort}
927    @r{strings using the locale's collating sequence.} */
928
929 void
930 sort_strings (char **array, int nstrings)
931 @{
932   /* @r{Sort @code{temp_array} by comparing the strings.} */
933   qsort (array, nstrings,
934          sizeof (char *), compare_elements);
935 @}
936 @end smallexample
937
938 @cindex converting string to collation order
939 @comment string.h
940 @comment ISO
941 @deftypefun size_t strxfrm (char *@var{to}, const char *@var{from}, size_t @var{size})
942 The function @code{strxfrm} transforms @var{string} using the collation
943 transformation determined by the locale currently selected for
944 collation, and stores the transformed string in the array @var{to}.  Up
945 to @var{size} characters (including a terminating null character) are
946 stored.
947
948 The behavior is undefined if the strings @var{to} and @var{from}
949 overlap; see @ref{Copying and Concatenation}.
950
951 The return value is the length of the entire transformed string.  This
952 value is not affected by the value of @var{size}, but if it is greater
953 or equal than @var{size}, it means that the transformed string did not
954 entirely fit in the array @var{to}.  In this case, only as much of the
955 string as actually fits was stored.  To get the whole transformed
956 string, call @code{strxfrm} again with a bigger output array.
957
958 The transformed string may be longer than the original string, and it
959 may also be shorter.
960
961 If @var{size} is zero, no characters are stored in @var{to}.  In this
962 case, @code{strxfrm} simply returns the number of characters that would
963 be the length of the transformed string.  This is useful for determining
964 what size string to allocate.  It does not matter what @var{to} is if
965 @var{size} is zero; @var{to} may even be a null pointer.
966 @end deftypefun
967
968 Here is an example of how you can use @code{strxfrm} when
969 you plan to do many comparisons.  It does the same thing as the previous
970 example, but much faster, because it has to transform each string only
971 once, no matter how many times it is compared with other strings.  Even
972 the time needed to allocate and free storage is much less than the time
973 we save, when there are many strings.
974
975 @smallexample
976 struct sorter @{ char *input; char *transformed; @};
977
978 /* @r{This is the comparison function used with @code{qsort}}
979    @r{to sort an array of @code{struct sorter}.} */
980
981 int
982 compare_elements (struct sorter *p1, struct sorter *p2)
983 @{
984   return strcmp (p1->transformed, p2->transformed);
985 @}
986
987 /* @r{This is the entry point---the function to sort}
988    @r{strings using the locale's collating sequence.} */
989
990 void
991 sort_strings_fast (char **array, int nstrings)
992 @{
993   struct sorter temp_array[nstrings];
994   int i;
995
996   /* @r{Set up @code{temp_array}.  Each element contains}
997      @r{one input string and its transformed string.} */
998   for (i = 0; i < nstrings; i++)
999     @{
1000       size_t length = strlen (array[i]) * 2;
1001       char *transformed;
1002       size_t transformed_length;
1003
1004       temp_array[i].input = array[i];
1005
1006       /* @r{First try a buffer perhaps big enough.}  */
1007       transformed = (char *) xmalloc (length);
1008
1009       /* @r{Transform @code{array[i]}.}  */
1010       transformed_length = strxfrm (transformed, array[i], length);
1011
1012       /* @r{If the buffer was not large enough, resize it}
1013          @r{and try again.}  */
1014       if (transformed_length >= length)
1015         @{
1016           /* @r{Allocate the needed space. +1 for terminating}
1017              @r{@code{NUL} character.}  */
1018           transformed = (char *) xrealloc (transformed,
1019                                            transformed_length + 1);
1020
1021           /* @r{The return value is not interesting because we know}
1022              @r{how long the transformed string is.}  */
1023           (void) strxfrm (transformed, array[i],
1024                           transformed_length + 1);
1025         @}
1026
1027       temp_array[i].transformed = transformed;
1028     @}
1029
1030   /* @r{Sort @code{temp_array} by comparing transformed strings.} */
1031   qsort (temp_array, sizeof (struct sorter),
1032          nstrings, compare_elements);
1033
1034   /* @r{Put the elements back in the permanent array}
1035      @r{in their sorted order.} */
1036   for (i = 0; i < nstrings; i++)
1037     array[i] = temp_array[i].input;
1038
1039   /* @r{Free the strings we allocated.} */
1040   for (i = 0; i < nstrings; i++)
1041     free (temp_array[i].transformed);
1042 @}
1043 @end smallexample
1044
1045 @strong{Compatibility Note:}  The string collation functions are a new
1046 feature of @w{ISO C90}.  Older C dialects have no equivalent feature.
1047
1048 @node Search Functions
1049 @section Search Functions
1050
1051 This section describes library functions which perform various kinds
1052 of searching operations on strings and arrays.  These functions are
1053 declared in the header file @file{string.h}.
1054 @pindex string.h
1055 @cindex search functions (for strings)
1056 @cindex string search functions
1057
1058 @comment string.h
1059 @comment ISO
1060 @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
1061 This function finds the first occurrence of the byte @var{c} (converted
1062 to an @code{unsigned char}) in the initial @var{size} bytes of the
1063 object beginning at @var{block}.  The return value is a pointer to the
1064 located byte, or a null pointer if no match was found.
1065 @end deftypefun
1066
1067 @comment string.h
1068 @comment GNU
1069 @deftypefun {void *} rawmemchr (const void *@var{block}, int @var{c})
1070 Often the @code{memchr} function is used with the knowledge that the
1071 byte @var{c} is available in the memory block specified by the
1072 parameters.  But this means that the @var{size} parameter is not really
1073 needed and that the tests performed with it at runtime (to check whether
1074 the end of the block is reached) are not needed.
1075
1076 The @code{rawmemchr} function exists for just this situation which is
1077 surprisingly frequent.  The interface is similar to @code{memchr} except
1078 that the @var{size} parameter is missing.  The function will look beyond
1079 the end of the block pointed to by @var{block} in case the programmer
1080 made an error in assuming that the byte @var{c} is present in the block.
1081 In this case the result is unspecified.  Otherwise the return value is a
1082 pointer to the located byte.
1083
1084 This function is of special interest when looking for the end of a
1085 string.  Since all strings are terminated by a null byte a call like
1086
1087 @smallexample
1088    rawmemchr (str, '\0')
1089 @end smallexample
1090
1091 will never go beyond the end of the string.
1092
1093 This function is a GNU extension.
1094 @end deftypefun
1095
1096 @comment string.h
1097 @comment GNU
1098 @deftypefun {void *} memrchr (const void *@var{block}, int @var{c}, size_t @var{size})
1099 The function @code{memrchr} is like @code{memchr}, except that it searches
1100 backwards from the end of the block defined by @var{block} and @var{size}
1101 (instead of forwards from the front).
1102 @end deftypefun
1103
1104 @comment string.h
1105 @comment ISO
1106 @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
1107 The @code{strchr} function finds the first occurrence of the character
1108 @var{c} (converted to a @code{char}) in the null-terminated string
1109 beginning at @var{string}.  The return value is a pointer to the located
1110 character, or a null pointer if no match was found.
1111
1112 For example,
1113 @smallexample
1114 strchr ("hello, world", 'l')
1115     @result{} "llo, world"
1116 strchr ("hello, world", '?')
1117     @result{} NULL
1118 @end smallexample
1119
1120 The terminating null character is considered to be part of the string,
1121 so you can use this function get a pointer to the end of a string by
1122 specifying a null character as the value of the @var{c} argument.
1123 @end deftypefun
1124
1125 @comment string.h
1126 @comment GNU
1127 @deftypefun {char *} strchrnul (const char *@var{string}, int @var{c})
1128 @code{strchrnul} is the same as @code{strchr} except that if it does
1129 not find the character, it returns a pointer to string's terminating
1130 null character rather than a null pointer.
1131 @end deftypefun
1132
1133 One useful, but unusual, use of the @code{strchr}
1134 function is when one wants to have a pointer pointing to the NUL byte
1135 terminating a string.  This is often written in this way:
1136
1137 @smallexample
1138   s += strlen (s);
1139 @end smallexample
1140
1141 @noindent
1142 This is almost optimal but the addition operation duplicated a bit of
1143 the work already done in the @code{strlen} function.  A better solution
1144 is this:
1145
1146 @smallexample
1147   s = strchr (s, '\0');
1148 @end smallexample
1149
1150 There is no restriction on the second parameter of @code{strchr} so it
1151 could very well also be the NUL character.  Those readers thinking very
1152 hard about this might now point out that the @code{strchr} function is
1153 more expensive than the @code{strlen} function since we have two abort
1154 criteria.  This is right.  But in the GNU C library the implementation of
1155 @code{strchr} is optimized in a special way so that @code{strchr}
1156 actually is faster.
1157
1158 @comment string.h
1159 @comment ISO
1160 @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
1161 The function @code{strrchr} is like @code{strchr}, except that it searches
1162 backwards from the end of the string @var{string} (instead of forwards
1163 from the front).
1164
1165 For example,
1166 @smallexample
1167 strrchr ("hello, world", 'l')
1168     @result{} "ld"
1169 @end smallexample
1170 @end deftypefun
1171
1172 @comment string.h
1173 @comment ISO
1174 @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
1175 This is like @code{strchr}, except that it searches @var{haystack} for a
1176 substring @var{needle} rather than just a single character.  It
1177 returns a pointer into the string @var{haystack} that is the first
1178 character of the substring, or a null pointer if no match was found.  If
1179 @var{needle} is an empty string, the function returns @var{haystack}.
1180
1181 For example,
1182 @smallexample
1183 strstr ("hello, world", "l")
1184     @result{} "llo, world"
1185 strstr ("hello, world", "wo")
1186     @result{} "world"
1187 @end smallexample
1188 @end deftypefun
1189
1190
1191 @comment string.h
1192 @comment ???
1193 @deftypefun {char *} strcasestr (const char *@var{haystack}, const char *@var{needle})
1194 This is like @code{strstr}, except that it ignores case in searching for
1195 the substring.   Like @code{strcasecmp}, it is locale dependent how
1196 uppercase and lowercase characters are related.
1197
1198
1199 For example,
1200 @smallexample
1201 strstr ("hello, world", "L")
1202     @result{} "llo, world"
1203 strstr ("hello, World", "wo")
1204     @result{} "World"
1205 @end smallexample
1206 @end deftypefun
1207
1208
1209 @comment string.h
1210 @comment GNU
1211 @deftypefun {void *} memmem (const void *@var{haystack}, size_t @var{haystack-len},@*const void *@var{needle}, size_t @var{needle-len})
1212 This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
1213 arrays rather than null-terminated strings.  @var{needle-len} is the
1214 length of @var{needle} and @var{haystack-len} is the length of
1215 @var{haystack}.@refill
1216
1217 This function is a GNU extension.
1218 @end deftypefun
1219
1220 @comment string.h
1221 @comment ISO
1222 @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
1223 The @code{strspn} (``string span'') function returns the length of the
1224 initial substring of @var{string} that consists entirely of characters that
1225 are members of the set specified by the string @var{skipset}.  The order
1226 of the characters in @var{skipset} is not important.
1227
1228 For example,
1229 @smallexample
1230 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
1231     @result{} 5
1232 @end smallexample
1233 @end deftypefun
1234
1235 @comment string.h
1236 @comment ISO
1237 @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
1238 The @code{strcspn} (``string complement span'') function returns the length
1239 of the initial substring of @var{string} that consists entirely of characters
1240 that are @emph{not} members of the set specified by the string @var{stopset}.
1241 (In other words, it returns the offset of the first character in @var{string}
1242 that is a member of the set @var{stopset}.)
1243
1244 For example,
1245 @smallexample
1246 strcspn ("hello, world", " \t\n,.;!?")
1247     @result{} 5
1248 @end smallexample
1249 @end deftypefun
1250
1251 @comment string.h
1252 @comment ISO
1253 @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
1254 The @code{strpbrk} (``string pointer break'') function is related to
1255 @code{strcspn}, except that it returns a pointer to the first character
1256 in @var{string} that is a member of the set @var{stopset} instead of the
1257 length of the initial substring.  It returns a null pointer if no such
1258 character from @var{stopset} is found.
1259
1260 @c @group  Invalid outside the example.
1261 For example,
1262
1263 @smallexample
1264 strpbrk ("hello, world", " \t\n,.;!?")
1265     @result{} ", world"
1266 @end smallexample
1267 @c @end group
1268 @end deftypefun
1269
1270
1271 @subsection Compatibility String Search Functions
1272
1273 @comment string.h
1274 @comment BSD
1275 @deftypefun {char *} index (const char *@var{string}, int @var{c})
1276 @code{index} is another name for @code{strchr}; they are exactly the same.
1277 New code should always use @code{strchr} since this name is defined in
1278 @w{ISO C} while @code{index} is a BSD invention which never was available
1279 on @w{System V} derived systems.
1280 @end deftypefun
1281
1282 @comment string.h
1283 @comment BSD
1284 @deftypefun {char *} rindex (const char *@var{string}, int @var{c})
1285 @code{rindex} is another name for @code{strrchr}; they are exactly the same.
1286 New code should always use @code{strrchr} since this name is defined in
1287 @w{ISO C} while @code{rindex} is a BSD invention which never was available
1288 on @w{System V} derived systems.
1289 @end deftypefun
1290
1291 @node Finding Tokens in a String
1292 @section Finding Tokens in a String
1293
1294 @cindex tokenizing strings
1295 @cindex breaking a string into tokens
1296 @cindex parsing tokens from a string
1297 It's fairly common for programs to have a need to do some simple kinds
1298 of lexical analysis and parsing, such as splitting a command string up
1299 into tokens.  You can do this with the @code{strtok} function, declared
1300 in the header file @file{string.h}.
1301 @pindex string.h
1302
1303 @comment string.h
1304 @comment ISO
1305 @deftypefun {char *} strtok (char *@var{newstring}, const char *@var{delimiters})
1306 A string can be split into tokens by making a series of calls to the
1307 function @code{strtok}.
1308
1309 The string to be split up is passed as the @var{newstring} argument on
1310 the first call only.  The @code{strtok} function uses this to set up
1311 some internal state information.  Subsequent calls to get additional
1312 tokens from the same string are indicated by passing a null pointer as
1313 the @var{newstring} argument.  Calling @code{strtok} with another
1314 non-null @var{newstring} argument reinitializes the state information.
1315 It is guaranteed that no other library function ever calls @code{strtok}
1316 behind your back (which would mess up this internal state information).
1317
1318 The @var{delimiters} argument is a string that specifies a set of delimiters
1319 that may surround the token being extracted.  All the initial characters
1320 that are members of this set are discarded.  The first character that is
1321 @emph{not} a member of this set of delimiters marks the beginning of the
1322 next token.  The end of the token is found by looking for the next
1323 character that is a member of the delimiter set.  This character in the
1324 original string @var{newstring} is overwritten by a null character, and the
1325 pointer to the beginning of the token in @var{newstring} is returned.
1326
1327 On the next call to @code{strtok}, the searching begins at the next
1328 character beyond the one that marked the end of the previous token.
1329 Note that the set of delimiters @var{delimiters} do not have to be the
1330 same on every call in a series of calls to @code{strtok}.
1331
1332 If the end of the string @var{newstring} is reached, or if the remainder of
1333 string consists only of delimiter characters, @code{strtok} returns
1334 a null pointer.
1335 @end deftypefun
1336
1337 @strong{Warning:} Since @code{strtok} alters the string it is parsing,
1338 you should always copy the string to a temporary buffer before parsing
1339 it with @code{strtok}.  If you allow @code{strtok} to modify a string
1340 that came from another part of your program, you are asking for trouble;
1341 that string might be used for other purposes after @code{strtok} has
1342 modified it, and it would not have the expected value.
1343
1344 The string that you are operating on might even be a constant.  Then
1345 when @code{strtok} tries to modify it, your program will get a fatal
1346 signal for writing in read-only memory.  @xref{Program Error Signals}.
1347 Even if the operation of @code{strtok} would not require a modification
1348 of the string (e.g., if there is exactly one token) the string can (and
1349 in the GNU libc case will) be modified.
1350
1351 This is a special case of a general principle: if a part of a program
1352 does not have as its purpose the modification of a certain data
1353 structure, then it is error-prone to modify the data structure
1354 temporarily.
1355
1356 The function @code{strtok} is not reentrant.  @xref{Nonreentrancy}, for
1357 a discussion of where and why reentrancy is important.
1358
1359 Here is a simple example showing the use of @code{strtok}.
1360
1361 @comment Yes, this example has been tested.
1362 @smallexample
1363 #include <string.h>
1364 #include <stddef.h>
1365
1366 @dots{}
1367
1368 const char string[] = "words separated by spaces -- and, punctuation!";
1369 const char delimiters[] = " .,;:!-";
1370 char *token, *cp;
1371
1372 @dots{}
1373
1374 cp = strdupa (string);                /* Make writable copy.  */
1375 token = strtok (cp, delimiters);      /* token => "words" */
1376 token = strtok (NULL, delimiters);    /* token => "separated" */
1377 token = strtok (NULL, delimiters);    /* token => "by" */
1378 token = strtok (NULL, delimiters);    /* token => "spaces" */
1379 token = strtok (NULL, delimiters);    /* token => "and" */
1380 token = strtok (NULL, delimiters);    /* token => "punctuation" */
1381 token = strtok (NULL, delimiters);    /* token => NULL */
1382 @end smallexample
1383
1384 The GNU C library contains two more functions for tokenizing a string
1385 which overcome the limitation of non-reentrancy.
1386
1387 @comment string.h
1388 @comment POSIX
1389 @deftypefun {char *} strtok_r (char *@var{newstring}, const char *@var{delimiters}, char **@var{save_ptr})
1390 Just like @code{strtok}, this function splits the string into several
1391 tokens which can be accessed by successive calls to @code{strtok_r}.
1392 The difference is that the information about the next token is stored in
1393 the space pointed to by the third argument, @var{save_ptr}, which is a
1394 pointer to a string pointer.  Calling @code{strtok_r} with a null
1395 pointer for @var{newstring} and leaving @var{save_ptr} between the calls
1396 unchanged does the job without hindering reentrancy.
1397
1398 This function is defined in POSIX.1 and can be found on many systems
1399 which support multi-threading.
1400 @end deftypefun
1401
1402 @comment string.h
1403 @comment BSD
1404 @deftypefun {char *} strsep (char **@var{string_ptr}, const char *@var{delimiter})
1405 This function has a similar functionality as @code{strtok_r} with the
1406 @var{newstring} argument replaced by the @var{save_ptr} argument.  The
1407 initialization of the moving pointer has to be done by the user.
1408 Successive calls to @code{strsep} move the pointer along the tokens
1409 separated by @var{delimiter}, returning the address of the next token
1410 and updating @var{string_ptr} to point to the beginning of the next
1411 token.
1412
1413 One difference between @code{strsep} and @code{strtok_r} is that if the
1414 input string contains more than one character from @var{delimiter} in a
1415 row @code{strsep} returns an empty string for each pair of characters
1416 from @var{delimiter}.  This means that a program normally should test
1417 for @code{strsep} returning an empty string before processing it.
1418
1419 This function was introduced in 4.3BSD and therefore is widely available.
1420 @end deftypefun
1421
1422 Here is how the above example looks like when @code{strsep} is used.
1423
1424 @comment Yes, this example has been tested.
1425 @smallexample
1426 #include <string.h>
1427 #include <stddef.h>
1428
1429 @dots{}
1430
1431 const char string[] = "words separated by spaces -- and, punctuation!";
1432 const char delimiters[] = " .,;:!-";
1433 char *running;
1434 char *token;
1435
1436 @dots{}
1437
1438 running = strdupa (string);
1439 token = strsep (&running, delimiters);    /* token => "words" */
1440 token = strsep (&running, delimiters);    /* token => "separated" */
1441 token = strsep (&running, delimiters);    /* token => "by" */
1442 token = strsep (&running, delimiters);    /* token => "spaces" */
1443 token = strsep (&running, delimiters);    /* token => "" */
1444 token = strsep (&running, delimiters);    /* token => "" */
1445 token = strsep (&running, delimiters);    /* token => "" */
1446 token = strsep (&running, delimiters);    /* token => "and" */
1447 token = strsep (&running, delimiters);    /* token => "" */
1448 token = strsep (&running, delimiters);    /* token => "punctuation" */
1449 token = strsep (&running, delimiters);    /* token => "" */
1450 token = strsep (&running, delimiters);    /* token => NULL */
1451 @end smallexample
1452
1453 @comment string.h
1454 @comment GNU
1455 @deftypefun {char *} basename (const char *@var{filename})
1456 The GNU version of the @code{basename} function returns the last
1457 component of the path in @var{filename}.  This function is the prefered
1458 usage, since it does not modify the argument, @var{filename}, and
1459 respects trailing slashes.  The prototype for @code{basename} can be
1460 found in @file{string.h}.  Note, this function is overriden by the XPG
1461 version, if @file{libgen.h} is included.
1462
1463 Example of using GNU @code{basename}:
1464
1465 @smallexample
1466 #include <string.h>
1467
1468 int
1469 main (int argc, char *argv[])
1470 @{
1471   char *prog = basename (argv[0]);
1472
1473   if (argc < 2)
1474     @{
1475       fprintf (stderr, "Usage %s <arg>\n", prog);
1476       exit (1);
1477     @}
1478
1479   @dots{}
1480 @}
1481 @end smallexample
1482
1483 @strong{Portability Note:} This function may produce different results
1484 on different systems.
1485
1486 @end deftypefun
1487
1488 @comment libgen.h
1489 @comment XPG
1490 @deftypefun {char *} basename (char *@var{path})
1491 This is the standard XPG defined @code{basename}. It is similar in
1492 spirit to the GNU version, but may modify the @var{path} by removing
1493 trailing '/' characters.  If the @var{path} is made up entirely of '/'
1494 characters, then "/" will be returned.  Also, if @var{path} is
1495 @code{NULL} or an empty string, then "." is returned.  The prototype for
1496 the XPG version can be found in @file{libgen.h}.
1497
1498 Example of using XPG @code{basename}:
1499
1500 @smallexample
1501 #include <libgen.h>
1502
1503 int
1504 main (int argc, char *argv[])
1505 @{
1506   char *prog;
1507   char *path = strdupa (argv[0]);
1508
1509   prog = basename (path);
1510
1511   if (argc < 2)
1512     @{
1513       fprintf (stderr, "Usage %s <arg>\n", prog);
1514       exit (1);
1515     @}
1516
1517   @dots{}
1518
1519 @}
1520 @end smallexample
1521 @end deftypefun
1522
1523 @comment libgen.h
1524 @comment XPG
1525 @deftypefun {char *} dirname (char *@var{path})
1526 The @code{dirname} function is the compliment to the XPG version of
1527 @code{basename}.  It returns the parent directory of the file specified
1528 by @var{path}.  If @var{path} is @code{NULL}, an empty string, or
1529 contains no '/' characters, then "." is returned.  The prototype for this
1530 function can be found in @file{libgen.h}.
1531 @end deftypefun
1532
1533 @node strfry
1534 @section strfry
1535
1536 The function below addresses the perennial programming quandary: ``How do
1537 I take good data in string form and painlessly turn it into garbage?''
1538 This is actually a fairly simple task for C programmers who do not use
1539 the GNU C library string functions, but for programs based on the GNU C
1540 library, the @code{strfry} function is the preferred method for
1541 destroying string data.
1542
1543 The prototype for this function is in @file{string.h}.
1544
1545 @comment string.h
1546 @comment GNU
1547 @deftypefun {char *} strfry (char *@var{string})
1548
1549 @code{strfry} creates a pseudorandom anagram of a string, replacing the
1550 input with the anagram in place.  For each position in the string,
1551 @code{strfry} swaps it with a position in the string selected at random
1552 (from a uniform distribution).  The two positions may be the same.
1553
1554 The return value of @code{strfry} is always @var{string}.
1555
1556 @strong{Portability Note:}  This function is unique to the GNU C library.
1557
1558 @end deftypefun
1559
1560
1561 @node Trivial Encryption
1562 @section Trivial Encryption
1563 @cindex encryption
1564
1565
1566 The @code{memfrob} function converts an array of data to something
1567 unrecognizable and back again.  It is not encryption in its usual sense
1568 since it is easy for someone to convert the encrypted data back to clear
1569 text.  The transformation is analogous to Usenet's ``Rot13'' encryption
1570 method for obscuring offensive jokes from sensitive eyes and such.
1571 Unlike Rot13, @code{memfrob} works on arbitrary binary data, not just
1572 text.
1573 @cindex Rot13
1574
1575 For true encryption, @xref{Cryptographic Functions}.
1576
1577 This function is declared in @file{string.h}.
1578 @pindex string.h
1579
1580 @comment string.h
1581 @comment GNU
1582 @deftypefun {void *} memfrob (void *@var{mem}, size_t @var{length})
1583
1584 @code{memfrob} transforms (frobnicates) each byte of the data structure
1585 at @var{mem}, which is @var{length} bytes long, by bitwise exclusive
1586 oring it with binary 00101010.  It does the transformation in place and
1587 its return value is always @var{mem}.
1588
1589 Note that @code{memfrob} a second time on the same data structure
1590 returns it to its original state.
1591
1592 This is a good function for hiding information from someone who doesn't
1593 want to see it or doesn't want to see it very much.  To really prevent
1594 people from retrieving the information, use stronger encryption such as
1595 that described in @xref{Cryptographic Functions}.
1596
1597 @strong{Portability Note:}  This function is unique to the GNU C library.
1598
1599 @end deftypefun
1600
1601 @node Encode Binary Data
1602 @section Encode Binary Data
1603
1604 To store or transfer binary data in environments which only support text
1605 one has to encode the binary data by mapping the input bytes to
1606 characters in the range allowed for storing or transfering.  SVID
1607 systems (and nowadays XPG compliant systems) provide minimal support for
1608 this task.
1609
1610 @comment stdlib.h
1611 @comment XPG
1612 @deftypefun {char *} l64a (long int @var{n})
1613 This function encodes a 32-bit input value using characters from the
1614 basic character set.  It returns a pointer to a 6 character buffer which
1615 contains an encoded version of @var{n}.  To encode a series of bytes the
1616 user must copy the returned string to a destination buffer.  It returns
1617 the empty string if @var{n} is zero, which is somewhat bizarre but
1618 mandated by the standard.@*
1619 @strong{Warning:} Since a static buffer is used this function should not
1620 be used in multi-threaded programs.  There is no thread-safe alternative
1621 to this function in the C library.@*
1622 @strong{Compatibility Note:} The XPG standard states that the return
1623 value of @code{l64a} is undefined if @var{n} is negative.  In the GNU
1624 implementation, @code{l64a} treats its argument as unsigned, so it will
1625 return a sensible encoding for any nonzero @var{n}; however, portable
1626 programs should not rely on this.
1627
1628 To encode a large buffer @code{l64a} must be called in a loop, once for
1629 each 32-bit word of the buffer.  For example, one could do something
1630 like this:
1631
1632 @smallexample
1633 char *
1634 encode (const void *buf, size_t len)
1635 @{
1636   /* @r{We know in advance how long the buffer has to be.} */
1637   unsigned char *in = (unsigned char *) buf;
1638   char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
1639   char *cp = out;
1640
1641   /* @r{Encode the length.} */
1642   /* @r{Using `htonl' is necessary so that the data can be}
1643      @r{decoded even on machines with different byte order.} */
1644
1645   cp = mempcpy (cp, l64a (htonl (len)), 6);
1646
1647   while (len > 3)
1648     @{
1649       unsigned long int n = *in++;
1650       n = (n << 8) | *in++;
1651       n = (n << 8) | *in++;
1652       n = (n << 8) | *in++;
1653       len -= 4;
1654       if (n)
1655         cp = mempcpy (cp, l64a (htonl (n)), 6);
1656       else
1657             /* @r{`l64a' returns the empty string for n==0, so we }
1658                @r{must generate its encoding (}"......"@r{) by hand.} */
1659         cp = stpcpy (cp, "......");
1660     @}
1661   if (len > 0)
1662     @{
1663       unsigned long int n = *in++;
1664       if (--len > 0)
1665         @{
1666           n = (n << 8) | *in++;
1667           if (--len > 0)
1668             n = (n << 8) | *in;
1669         @}
1670       memcpy (cp, l64a (htonl (n)), 6);
1671       cp += 6;
1672     @}
1673   *cp = '\0';
1674   return out;
1675 @}
1676 @end smallexample
1677
1678 It is strange that the library does not provide the complete
1679 functionality needed but so be it.
1680
1681 @end deftypefun
1682
1683 To decode data produced with @code{l64a} the following function should be
1684 used.
1685
1686 @comment stdlib.h
1687 @comment XPG
1688 @deftypefun {long int} a64l (const char *@var{string})
1689 The parameter @var{string} should contain a string which was produced by
1690 a call to @code{l64a}.  The function processes at least 6 characters of
1691 this string, and decodes the characters it finds according to the table
1692 below.  It stops decoding when it finds a character not in the table,
1693 rather like @code{atoi}; if you have a buffer which has been broken into
1694 lines, you must be careful to skip over the end-of-line characters.
1695
1696 The decoded number is returned as a @code{long int} value.
1697 @end deftypefun
1698
1699 The @code{l64a} and @code{a64l} functions use a base 64 encoding, in
1700 which each character of an encoded string represents six bits of an
1701 input word.  These symbols are used for the base 64 digits:
1702
1703 @multitable {xxxxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx}
1704 @item              @tab 0 @tab 1 @tab 2 @tab 3 @tab 4 @tab 5 @tab 6 @tab 7
1705 @item       0      @tab @code{.} @tab @code{/} @tab @code{0} @tab @code{1}
1706                    @tab @code{2} @tab @code{3} @tab @code{4} @tab @code{5}
1707 @item       8      @tab @code{6} @tab @code{7} @tab @code{8} @tab @code{9}
1708                    @tab @code{A} @tab @code{B} @tab @code{C} @tab @code{D}
1709 @item       16     @tab @code{E} @tab @code{F} @tab @code{G} @tab @code{H}
1710                    @tab @code{I} @tab @code{J} @tab @code{K} @tab @code{L}
1711 @item       24     @tab @code{M} @tab @code{N} @tab @code{O} @tab @code{P}
1712                    @tab @code{Q} @tab @code{R} @tab @code{S} @tab @code{T}
1713 @item       32     @tab @code{U} @tab @code{V} @tab @code{W} @tab @code{X}
1714                    @tab @code{Y} @tab @code{Z} @tab @code{a} @tab @code{b}
1715 @item       40     @tab @code{c} @tab @code{d} @tab @code{e} @tab @code{f}
1716                    @tab @code{g} @tab @code{h} @tab @code{i} @tab @code{j}
1717 @item       48     @tab @code{k} @tab @code{l} @tab @code{m} @tab @code{n}
1718                    @tab @code{o} @tab @code{p} @tab @code{q} @tab @code{r}
1719 @item       56     @tab @code{s} @tab @code{t} @tab @code{u} @tab @code{v}
1720                    @tab @code{w} @tab @code{x} @tab @code{y} @tab @code{z}
1721 @end multitable
1722
1723 This encoding scheme is not standard.  There are some other encoding
1724 methods which are much more widely used (UU encoding, MIME encoding).
1725 Generally, it is better to use one of these encodings.
1726
1727 @node Argz and Envz Vectors
1728 @section Argz and Envz Vectors
1729
1730 @cindex argz vectors (string vectors)
1731 @cindex string vectors, null-character separated
1732 @cindex argument vectors, null-character separated
1733 @dfn{argz vectors} are vectors of strings in a contiguous block of
1734 memory, each element separated from its neighbors by null-characters
1735 (@code{'\0'}).
1736
1737 @cindex envz vectors (environment vectors)
1738 @cindex environment vectors, null-character separated
1739 @dfn{Envz vectors} are an extension of argz vectors where each element is a
1740 name-value pair, separated by a @code{'='} character (as in a Unix
1741 environment).
1742
1743 @menu
1744 * Argz Functions::              Operations on argz vectors.
1745 * Envz Functions::              Additional operations on environment vectors.
1746 @end menu
1747
1748 @node Argz Functions, Envz Functions, , Argz and Envz Vectors
1749 @subsection Argz Functions
1750
1751 Each argz vector is represented by a pointer to the first element, of
1752 type @code{char *}, and a size, of type @code{size_t}, both of which can
1753 be initialized to @code{0} to represent an empty argz vector.  All argz
1754 functions accept either a pointer and a size argument, or pointers to
1755 them, if they will be modified.
1756
1757 The argz functions use @code{malloc}/@code{realloc} to allocate/grow
1758 argz vectors, and so any argz vector creating using these functions may
1759 be freed by using @code{free}; conversely, any argz function that may
1760 grow a string expects that string to have been allocated using
1761 @code{malloc} (those argz functions that only examine their arguments or
1762 modify them in place will work on any sort of memory).
1763 @xref{Unconstrained Allocation}.
1764
1765 All argz functions that do memory allocation have a return type of
1766 @code{error_t}, and return @code{0} for success, and @code{ENOMEM} if an
1767 allocation error occurs.
1768
1769 @pindex argz.h
1770 These functions are declared in the standard include file @file{argz.h}.
1771
1772 @comment argz.h
1773 @comment GNU
1774 @deftypefun {error_t} argz_create (char *const @var{argv}[], char **@var{argz}, size_t *@var{argz_len})
1775 The @code{argz_create} function converts the Unix-style argument vector
1776 @var{argv} (a vector of pointers to normal C strings, terminated by
1777 @code{(char *)0}; @pxref{Program Arguments}) into an argz vector with
1778 the same elements, which is returned in @var{argz} and @var{argz_len}.
1779 @end deftypefun
1780
1781 @comment argz.h
1782 @comment GNU
1783 @deftypefun {error_t} argz_create_sep (const char *@var{string}, int @var{sep}, char **@var{argz}, size_t *@var{argz_len})
1784 The @code{argz_create_sep} function converts the null-terminated string
1785 @var{string} into an argz vector (returned in @var{argz} and
1786 @var{argz_len}) by splitting it into elements at every occurrence of the
1787 character @var{sep}.
1788 @end deftypefun
1789
1790 @comment argz.h
1791 @comment GNU
1792 @deftypefun {size_t} argz_count (const char *@var{argz}, size_t @var{arg_len})
1793 Returns the number of elements in the argz vector @var{argz} and
1794 @var{argz_len}.
1795 @end deftypefun
1796
1797 @comment argz.h
1798 @comment GNU
1799 @deftypefun {void} argz_extract (char *@var{argz}, size_t @var{argz_len}, char **@var{argv})
1800 The @code{argz_extract} function converts the argz vector @var{argz} and
1801 @var{argz_len} into a Unix-style argument vector stored in @var{argv},
1802 by putting pointers to every element in @var{argz} into successive
1803 positions in @var{argv}, followed by a terminator of @code{0}.
1804 @var{Argv} must be pre-allocated with enough space to hold all the
1805 elements in @var{argz} plus the terminating @code{(char *)0}
1806 (@code{(argz_count (@var{argz}, @var{argz_len}) + 1) * sizeof (char *)}
1807 bytes should be enough).  Note that the string pointers stored into
1808 @var{argv} point into @var{argz}---they are not copies---and so
1809 @var{argz} must be copied if it will be changed while @var{argv} is
1810 still active.  This function is useful for passing the elements in
1811 @var{argz} to an exec function (@pxref{Executing a File}).
1812 @end deftypefun
1813
1814 @comment argz.h
1815 @comment GNU
1816 @deftypefun {void} argz_stringify (char *@var{argz}, size_t @var{len}, int @var{sep})
1817 The @code{argz_stringify} converts @var{argz} into a normal string with
1818 the elements separated by the character @var{sep}, by replacing each
1819 @code{'\0'} inside @var{argz} (except the last one, which terminates the
1820 string) with @var{sep}.  This is handy for printing @var{argz} in a
1821 readable manner.
1822 @end deftypefun
1823
1824 @comment argz.h
1825 @comment GNU
1826 @deftypefun {error_t} argz_add (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str})
1827 The @code{argz_add} function adds the string @var{str} to the end of the
1828 argz vector @code{*@var{argz}}, and updates @code{*@var{argz}} and
1829 @code{*@var{argz_len}} accordingly.
1830 @end deftypefun
1831
1832 @comment argz.h
1833 @comment GNU
1834 @deftypefun {error_t} argz_add_sep (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str}, int @var{delim})
1835 The @code{argz_add_sep} function is similar to @code{argz_add}, but
1836 @var{str} is split into separate elements in the result at occurrences of
1837 the character @var{delim}.  This is useful, for instance, for
1838 adding the components of a Unix search path to an argz vector, by using
1839 a value of @code{':'} for @var{delim}.
1840 @end deftypefun
1841
1842 @comment argz.h
1843 @comment GNU
1844 @deftypefun {error_t} argz_append (char **@var{argz}, size_t *@var{argz_len}, const char *@var{buf}, size_t @var{buf_len})
1845 The @code{argz_append} function appends @var{buf_len} bytes starting at
1846 @var{buf} to the argz vector @code{*@var{argz}}, reallocating
1847 @code{*@var{argz}} to accommodate it, and adding @var{buf_len} to
1848 @code{*@var{argz_len}}.
1849 @end deftypefun
1850
1851 @comment argz.h
1852 @comment GNU
1853 @deftypefun {error_t} argz_delete (char **@var{argz}, size_t *@var{argz_len}, char *@var{entry})
1854 If @var{entry} points to the beginning of one of the elements in the
1855 argz vector @code{*@var{argz}}, the @code{argz_delete} function will
1856 remove this entry and reallocate @code{*@var{argz}}, modifying
1857 @code{*@var{argz}} and @code{*@var{argz_len}} accordingly.  Note that as
1858 destructive argz functions usually reallocate their argz argument,
1859 pointers into argz vectors such as @var{entry} will then become invalid.
1860 @end deftypefun
1861
1862 @comment argz.h
1863 @comment GNU
1864 @deftypefun {error_t} argz_insert (char **@var{argz}, size_t *@var{argz_len}, char *@var{before}, const char *@var{entry})
1865 The @code{argz_insert} function inserts the string @var{entry} into the
1866 argz vector @code{*@var{argz}} at a point just before the existing
1867 element pointed to by @var{before}, reallocating @code{*@var{argz}} and
1868 updating @code{*@var{argz}} and @code{*@var{argz_len}}.  If @var{before}
1869 is @code{0}, @var{entry} is added to the end instead (as if by
1870 @code{argz_add}).  Since the first element is in fact the same as
1871 @code{*@var{argz}}, passing in @code{*@var{argz}} as the value of
1872 @var{before} will result in @var{entry} being inserted at the beginning.
1873 @end deftypefun
1874
1875 @comment argz.h
1876 @comment GNU
1877 @deftypefun {char *} argz_next (char *@var{argz}, size_t @var{argz_len}, const char *@var{entry})
1878 The @code{argz_next} function provides a convenient way of iterating
1879 over the elements in the argz vector @var{argz}.  It returns a pointer
1880 to the next element in @var{argz} after the element @var{entry}, or
1881 @code{0} if there are no elements following @var{entry}.  If @var{entry}
1882 is @code{0}, the first element of @var{argz} is returned.
1883
1884 This behavior suggests two styles of iteration:
1885
1886 @smallexample
1887     char *entry = 0;
1888     while ((entry = argz_next (@var{argz}, @var{argz_len}, entry)))
1889       @var{action};
1890 @end smallexample
1891
1892 (the double parentheses are necessary to make some C compilers shut up
1893 about what they consider a questionable @code{while}-test) and:
1894
1895 @smallexample
1896     char *entry;
1897     for (entry = @var{argz};
1898          entry;
1899          entry = argz_next (@var{argz}, @var{argz_len}, entry))
1900       @var{action};
1901 @end smallexample
1902
1903 Note that the latter depends on @var{argz} having a value of @code{0} if
1904 it is empty (rather than a pointer to an empty block of memory); this
1905 invariant is maintained for argz vectors created by the functions here.
1906 @end deftypefun
1907
1908 @comment argz.h
1909 @comment GNU
1910 @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}})
1911 Replace any occurrences of the string @var{str} in @var{argz} with
1912 @var{with}, reallocating @var{argz} as necessary.  If
1913 @var{replace_count} is non-zero, @code{*@var{replace_count}} will be
1914 incremented by number of replacements performed.
1915 @end deftypefun
1916
1917 @node Envz Functions, , Argz Functions, Argz and Envz Vectors
1918 @subsection Envz Functions
1919
1920 Envz vectors are just argz vectors with additional constraints on the form
1921 of each element; as such, argz functions can also be used on them, where it
1922 makes sense.
1923
1924 Each element in an envz vector is a name-value pair, separated by a @code{'='}
1925 character; if multiple @code{'='} characters are present in an element, those
1926 after the first are considered part of the value, and treated like all other
1927 non-@code{'\0'} characters.
1928
1929 If @emph{no} @code{'='} characters are present in an element, that element is
1930 considered the name of a ``null'' entry, as distinct from an entry with an
1931 empty value: @code{envz_get} will return @code{0} if given the name of null
1932 entry, whereas an entry with an empty value would result in a value of
1933 @code{""}; @code{envz_entry} will still find such entries, however.  Null
1934 entries can be removed with @code{envz_strip} function.
1935
1936 As with argz functions, envz functions that may allocate memory (and thus
1937 fail) have a return type of @code{error_t}, and return either @code{0} or
1938 @code{ENOMEM}.
1939
1940 @pindex envz.h
1941 These functions are declared in the standard include file @file{envz.h}.
1942
1943 @comment envz.h
1944 @comment GNU
1945 @deftypefun {char *} envz_entry (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
1946 The @code{envz_entry} function finds the entry in @var{envz} with the name
1947 @var{name}, and returns a pointer to the whole entry---that is, the argz
1948 element which begins with @var{name} followed by a @code{'='} character.  If
1949 there is no entry with that name, @code{0} is returned.
1950 @end deftypefun
1951
1952 @comment envz.h
1953 @comment GNU
1954 @deftypefun {char *} envz_get (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
1955 The @code{envz_get} function finds the entry in @var{envz} with the name
1956 @var{name} (like @code{envz_entry}), and returns a pointer to the value
1957 portion of that entry (following the @code{'='}).  If there is no entry with
1958 that name (or only a null entry), @code{0} is returned.
1959 @end deftypefun
1960
1961 @comment envz.h
1962 @comment GNU
1963 @deftypefun {error_t} envz_add (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name}, const char *@var{value})
1964 The @code{envz_add} function adds an entry to @code{*@var{envz}}
1965 (updating @code{*@var{envz}} and @code{*@var{envz_len}}) with the name
1966 @var{name}, and value @var{value}.  If an entry with the same name
1967 already exists in @var{envz}, it is removed first.  If @var{value} is
1968 @code{0}, then the new entry will the special null type of entry
1969 (mentioned above).
1970 @end deftypefun
1971
1972 @comment envz.h
1973 @comment GNU
1974 @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})
1975 The @code{envz_merge} function adds each entry in @var{envz2} to @var{envz},
1976 as if with @code{envz_add}, updating @code{*@var{envz}} and
1977 @code{*@var{envz_len}}.  If @var{override} is true, then values in @var{envz2}
1978 will supersede those with the same name in @var{envz}, otherwise not.
1979
1980 Null entries are treated just like other entries in this respect, so a null
1981 entry in @var{envz} can prevent an entry of the same name in @var{envz2} from
1982 being added to @var{envz}, if @var{override} is false.
1983 @end deftypefun
1984
1985 @comment envz.h
1986 @comment GNU
1987 @deftypefun {void} envz_strip (char **@var{envz}, size_t *@var{envz_len})
1988 The @code{envz_strip} function removes any null entries from @var{envz},
1989 updating @code{*@var{envz}} and @code{*@var{envz_len}}.
1990 @end deftypefun