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