Update.
[glibc.git] / manual / string.texi
blobdd3c68d2941421998eedb829f2f8e9021e3cbda7
1 @node String and Array Utilities, Extended Characters, Character Handling, Top
2 @chapter String and Array Utilities
4 Operations on strings (or arrays of characters) are an important part of
5 many programs.  The GNU C library provides an extensive set of string
6 utility functions, including functions for copying, concatenating,
7 comparing, and searching strings.  Many of these functions can also
8 operate on arbitrary regions of storage; for example, the @code{memcpy}
9 function can be used to copy the contents of any kind of array.
11 It's fairly common for beginning C programmers to ``reinvent the wheel''
12 by duplicating this functionality in their own code, but it pays to
13 become familiar with the library functions and to make use of them,
14 since this offers benefits in maintenance, efficiency, and portability.
16 For instance, you could easily compare one string to another in two
17 lines of C code, but if you use the built-in @code{strcmp} function,
18 you're less likely to make a mistake.  And, since these library
19 functions are typically highly optimized, your program may run faster
20 too.
22 @menu
23 * Representation of Strings::   Introduction to basic concepts.
24 * String/Array Conventions::    Whether to use a string function or an
25                                  arbitrary array function.
26 * String Length::               Determining the length of a string.
27 * Copying and Concatenation::   Functions to copy the contents of strings
28                                  and arrays.
29 * String/Array Comparison::     Functions for byte-wise and character-wise
30                                  comparison.
31 * Collation Functions::         Functions for collating strings.
32 * Search Functions::            Searching for a specific element or substring.
33 * Finding Tokens in a String::  Splitting a string into tokens by looking
34                                  for delimiters.
35 * Encode Binary Data::          Encoding and Decoding of Binary Data.
36 * Argz and Envz Vectors::       Null-separated string vectors.
37 @end menu
39 @node Representation of Strings
40 @section Representation of Strings
41 @cindex string, representation of
43 This section is a quick summary of string concepts for beginning C
44 programmers.  It describes how character strings are represented in C
45 and some common pitfalls.  If you are already familiar with this
46 material, you can skip this section.
48 @cindex string
49 @cindex null character
50 A @dfn{string} is an array of @code{char} objects.  But string-valued
51 variables are usually declared to be pointers of type @code{char *}.
52 Such variables do not include space for the text of a string; that has
53 to be stored somewhere else---in an array variable, a string constant,
54 or dynamically allocated memory (@pxref{Memory Allocation}).  It's up to
55 you to store the address of the chosen memory space into the pointer
56 variable.  Alternatively you can store a @dfn{null pointer} in the
57 pointer variable.  The null pointer does not point anywhere, so
58 attempting to reference the string it points to gets an error.
60 By convention, a @dfn{null character}, @code{'\0'}, marks the end of a
61 string.  For example, in testing to see whether the @code{char *}
62 variable @var{p} points to a null character marking the end of a string,
63 you can write @code{!*@var{p}} or @code{*@var{p} == '\0'}.
65 A null character is quite different conceptually from a null pointer,
66 although both are represented by the integer @code{0}.
68 @cindex string literal
69 @dfn{String literals} appear in C program source as strings of
70 characters between double-quote characters (@samp{"}).  In @w{ISO C},
71 string literals can also be formed by @dfn{string concatenation}:
72 @code{"a" "b"} is the same as @code{"ab"}.  Modification of string
73 literals is not allowed by the GNU C compiler, because literals
74 are placed in read-only storage.
76 Character arrays that are declared @code{const} cannot be modified
77 either.  It's generally good style to declare non-modifiable string
78 pointers to be of type @code{const char *}, since this often allows the
79 C compiler to detect accidental modifications as well as providing some
80 amount of documentation about what your program intends to do with the
81 string.
83 The amount of memory allocated for the character array may extend past
84 the null character that normally marks the end of the string.  In this
85 document, the term @dfn{allocated size} is always used to refer to the
86 total amount of memory allocated for the string, while the term
87 @dfn{length} refers to the number of characters up to (but not
88 including) the terminating null character.
89 @cindex length of string
90 @cindex allocation size of string
91 @cindex size of string
92 @cindex string length
93 @cindex string allocation
95 A notorious source of program bugs is trying to put more characters in a
96 string than fit in its allocated size.  When writing code that extends
97 strings or moves characters into a pre-allocated array, you should be
98 very careful to keep track of the length of the text and make explicit
99 checks for overflowing the array.  Many of the library functions
100 @emph{do not} do this for you!  Remember also that you need to allocate
101 an extra byte to hold the null character that marks the end of the
102 string.
104 @node String/Array Conventions
105 @section String and Array Conventions
107 This chapter describes both functions that work on arbitrary arrays or
108 blocks of memory, and functions that are specific to null-terminated
109 arrays of characters.
111 Functions that operate on arbitrary blocks of memory have names
112 beginning with @samp{mem} (such as @code{memcpy}) and invariably take an
113 argument which specifies the size (in bytes) of the block of memory to
114 operate on.  The array arguments and return values for these functions
115 have type @code{void *}, and as a matter of style, the elements of these
116 arrays are referred to as ``bytes''.  You can pass any kind of pointer
117 to these functions, and the @code{sizeof} operator is useful in
118 computing the value for the size argument.
120 In contrast, functions that operate specifically on strings have names
121 beginning with @samp{str} (such as @code{strcpy}) and look for a null
122 character to terminate the string instead of requiring an explicit size
123 argument to be passed.  (Some of these functions accept a specified
124 maximum length, but they also check for premature termination with a
125 null character.)  The array arguments and return values for these
126 functions have type @code{char *}, and the array elements are referred
127 to as ``characters''.
129 In many cases, there are both @samp{mem} and @samp{str} versions of a
130 function.  The one that is more appropriate to use depends on the exact
131 situation.  When your program is manipulating arbitrary arrays or blocks of
132 storage, then you should always use the @samp{mem} functions.  On the
133 other hand, when you are manipulating null-terminated strings it is
134 usually more convenient to use the @samp{str} functions, unless you
135 already know the length of the string in advance.
137 @node String Length
138 @section String Length
140 You can get the length of a string using the @code{strlen} function.
141 This function is declared in the header file @file{string.h}.
142 @pindex string.h
144 @comment string.h
145 @comment ISO
146 @deftypefun size_t strlen (const char *@var{s})
147 The @code{strlen} function returns the length of the null-terminated
148 string @var{s}.  (In other words, it returns the offset of the terminating
149 null character within the array.)
151 For example,
152 @smallexample
153 strlen ("hello, world")
154     @result{} 12
155 @end smallexample
157 When applied to a character array, the @code{strlen} function returns
158 the length of the string stored there, not its allocated size.  You can
159 get the allocated size of the character array that holds a string using
160 the @code{sizeof} operator:
162 @smallexample
163 char string[32] = "hello, world";
164 sizeof (string)
165     @result{} 32
166 strlen (string)
167     @result{} 12
168 @end smallexample
170 But beware, this will not work unless @var{string} is the character
171 array itself, not a pointer to it.  For example:
173 @smallexample
174 char string[32] = "hello, world";
175 char *ptr = string;
176 sizeof (string)
177     @result{} 32
178 sizeof (ptr)
179     @result{} 4  /* @r{(on a machine with 4 byte pointers)} */
180 @end smallexample
182 This is an easy mistake to make when you are working with functions that
183 take string arguments; those arguments are always pointers, not arrays.
185 @end deftypefun
187 @comment string.h
188 @comment GNU
189 @deftypefun size_t strnlen (const char *@var{s}, size_t @var{maxlen})
190 The @code{strnlen} function returns the length of the null-terminated
191 string @var{s} is this length is smaller than @var{maxlen}.  Otherwise
192 it returns @var{maxlen}.  Therefore this function is equivalent to
193 @code{(strlen (@var{s}) < n ? strlen (@var{s}) : @var{maxlen})} but it
194 is more efficient.
196 @smallexample
197 char string[32] = "hello, world";
198 strnlen (string, 32)
199     @result{} 12
200 strnlen (string, 5)
201     @result{} 5
202 @end smallexample
204 This function is a GNU extension.
205 @end deftypefun
207 @node Copying and Concatenation
208 @section Copying and Concatenation
210 You can use the functions described in this section to copy the contents
211 of strings and arrays, or to append the contents of one string to
212 another.  These functions are declared in the header file
213 @file{string.h}.
214 @pindex string.h
215 @cindex copying strings and arrays
216 @cindex string copy functions
217 @cindex array copy functions
218 @cindex concatenating strings
219 @cindex string concatenation functions
221 A helpful way to remember the ordering of the arguments to the functions
222 in this section is that it corresponds to an assignment expression, with
223 the destination array specified to the left of the source array.  All
224 of these functions return the address of the destination array.
226 Most of these functions do not work properly if the source and
227 destination arrays overlap.  For example, if the beginning of the
228 destination array overlaps the end of the source array, the original
229 contents of that part of the source array may get overwritten before it
230 is copied.  Even worse, in the case of the string functions, the null
231 character marking the end of the string may be lost, and the copy
232 function might get stuck in a loop trashing all the memory allocated to
233 your program.
235 All functions that have problems copying between overlapping arrays are
236 explicitly identified in this manual.  In addition to functions in this
237 section, there are a few others like @code{sprintf} (@pxref{Formatted
238 Output Functions}) and @code{scanf} (@pxref{Formatted Input
239 Functions}).
241 @comment string.h
242 @comment ISO
243 @deftypefun {void *} memcpy (void *@var{to}, const void *@var{from}, size_t @var{size})
244 The @code{memcpy} function copies @var{size} bytes from the object
245 beginning at @var{from} into the object beginning at @var{to}.  The
246 behavior of this function is undefined if the two arrays @var{to} and
247 @var{from} overlap; use @code{memmove} instead if overlapping is possible.
249 The value returned by @code{memcpy} is the value of @var{to}.
251 Here is an example of how you might use @code{memcpy} to copy the
252 contents of an array:
254 @smallexample
255 struct foo *oldarray, *newarray;
256 int arraysize;
257 @dots{}
258 memcpy (new, old, arraysize * sizeof (struct foo));
259 @end smallexample
260 @end deftypefun
262 @comment string.h
263 @comment GNU
264 @deftypefun {void *} mempcpy (void *@var{to}, const void *@var{from}, size_t @var{size})
265 The @code{mempcpy} function is nearly identical to the @code{memcpy}
266 function.  It copies @var{size} bytes from the object beginning at
267 @code{from} into the object pointed to by @var{to}.  But instead of
268 returning the value of @code{to} it returns a pointer to the byte
269 following the last written byte in the object beginning at @var{to}.
270 I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
272 This function is useful in situations where a number of objects shall be
273 copied to consecutive memory positions.
275 @smallexample
276 void *
277 combine (void *o1, size_t s1, void *o2, size_t s2)
279   void *result = malloc (s1 + s2);
280   if (result != NULL)
281     mempcpy (mempcpy (result, o1, s1), o2, s2);
282   return result;
284 @end smallexample
286 This function is a GNU extension.
287 @end deftypefun
289 @comment string.h
290 @comment ISO
291 @deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
292 @code{memmove} copies the @var{size} bytes at @var{from} into the
293 @var{size} bytes at @var{to}, even if those two blocks of space
294 overlap.  In the case of overlap, @code{memmove} is careful to copy the
295 original values of the bytes in the block at @var{from}, including those
296 bytes which also belong to the block at @var{to}.
297 @end deftypefun
299 @comment string.h
300 @comment SVID
301 @deftypefun {void *} memccpy (void *@var{to}, const void *@var{from}, int @var{c}, size_t @var{size})
302 This function copies no more than @var{size} bytes from @var{from} to
303 @var{to}, stopping if a byte matching @var{c} is found.  The return
304 value is a pointer into @var{to} one byte past where @var{c} was copied,
305 or a null pointer if no byte matching @var{c} appeared in the first
306 @var{size} bytes of @var{from}.
307 @end deftypefun
309 @comment string.h
310 @comment ISO
311 @deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
312 This function copies the value of @var{c} (converted to an
313 @code{unsigned char}) into each of the first @var{size} bytes of the
314 object beginning at @var{block}.  It returns the value of @var{block}.
315 @end deftypefun
317 @comment string.h
318 @comment ISO
319 @deftypefun {char *} strcpy (char *@var{to}, const char *@var{from})
320 This copies characters from the string @var{from} (up to and including
321 the terminating null character) into the string @var{to}.  Like
322 @code{memcpy}, this function has undefined results if the strings
323 overlap.  The return value is the value of @var{to}.
324 @end deftypefun
326 @comment string.h
327 @comment ISO
328 @deftypefun {char *} strncpy (char *@var{to}, const char *@var{from}, size_t @var{size})
329 This function is similar to @code{strcpy} but always copies exactly
330 @var{size} characters into @var{to}.
332 If the length of @var{from} is more than @var{size}, then @code{strncpy}
333 copies just the first @var{size} characters.  Note that in this case
334 there is no null terminator written into @var{to}.
336 If the length of @var{from} is less than @var{size}, then @code{strncpy}
337 copies all of @var{from}, followed by enough null characters to add up
338 to @var{size} characters in all.  This behavior is rarely useful, but it
339 is specified by the @w{ISO C} standard.
341 The behavior of @code{strncpy} is undefined if the strings overlap.
343 Using @code{strncpy} as opposed to @code{strcpy} is a way to avoid bugs
344 relating to writing past the end of the allocated space for @var{to}.
345 However, it can also make your program much slower in one common case:
346 copying a string which is probably small into a potentially large buffer.
347 In this case, @var{size} may be large, and when it is, @code{strncpy} will
348 waste a considerable amount of time copying null characters.
349 @end deftypefun
351 @comment string.h
352 @comment SVID
353 @deftypefun {char *} strdup (const char *@var{s})
354 This function copies the null-terminated string @var{s} into a newly
355 allocated string.  The string is allocated using @code{malloc}; see
356 @ref{Unconstrained Allocation}.  If @code{malloc} cannot allocate space
357 for the new string, @code{strdup} returns a null pointer.  Otherwise it
358 returns a pointer to the new string.
359 @end deftypefun
361 @comment string.h
362 @comment GNU
363 @deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
364 This function is similar to @code{strdup} but always copies at most
365 @var{size} characters into the newly allocated string.
367 If the length of @var{s} is more than @var{size}, then @code{strndup}
368 copies just the first @var{size} characters and adds a closing null
369 terminator.  Otherwise all characters are copied and the string is
370 terminated.
372 This function is different to @code{strncpy} in that it always
373 terminates the destination string.
374 @end deftypefun
376 @comment string.h
377 @comment Unknown origin
378 @deftypefun {char *} stpcpy (char *@var{to}, const char *@var{from})
379 This function is like @code{strcpy}, except that it returns a pointer to
380 the end of the string @var{to} (that is, the address of the terminating
381 null character) rather than the beginning.
383 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
384 and @samp{bar} to produce @samp{foobar}, which it then prints.
386 @smallexample
387 @include stpcpy.c.texi
388 @end smallexample
390 This function is not part of the ISO or POSIX standards, and is not
391 customary on Unix systems, but we did not invent it either.  Perhaps it
392 comes from MS-DOG.
394 Its behavior is undefined if the strings overlap.
395 @end deftypefun
397 @comment string.h
398 @comment GNU
399 @deftypefun {char *} stpncpy (char *@var{to}, const char *@var{from}, size_t @var{size})
400 This function is similar to @code{stpcpy} but copies always exactly
401 @var{size} characters into @var{to}.
403 If the length of @var{from} is more then @var{size}, then @code{stpncpy}
404 copies just the first @var{size} characters and returns a pointer to the
405 character directly following the one which was copied last.  Note that in
406 this case there is no null terminator written into @var{to}.
408 If the length of @var{from} is less than @var{size}, then @code{stpncpy}
409 copies all of @var{from}, followed by enough null characters to add up
410 to @var{size} characters in all.  This behaviour is rarely useful, but it
411 is implemented to be useful in contexts where this behaviour of the
412 @code{strncpy} is used.  @code{stpncpy} returns a pointer to the
413 @emph{first} written null character.
415 This function is not part of ISO or POSIX but was found useful while
416 developing the GNU C Library itself.
418 Its behaviour is undefined if the strings overlap.
419 @end deftypefun
421 @comment string.h
422 @comment GNU
423 @deftypefn {Macro} {char *} strdupa (const char *@var{s})
424 This function is similar to @code{strdup} but allocates the new string
425 using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
426 Automatic}).  This means of course the returned string has the same
427 limitations as any block of memory allocated using @code{alloca}.
429 For obvious reasons @code{strdupa} is implemented only as a macro;
430 you cannot get the address of this function.  Despite this limitation
431 it is a useful function.  The following code shows a situation where
432 using @code{malloc} would be a lot more expensive.
434 @smallexample
435 @include strdupa.c.texi
436 @end smallexample
438 Please note that calling @code{strtok} using @var{path} directly is
439 invalid.
441 This function is only available if GNU CC is used.
442 @end deftypefn
444 @comment string.h
445 @comment GNU
446 @deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
447 This function is similar to @code{strndup} but like @code{strdupa} it
448 allocates the new string using @code{alloca}
449 @pxref{Variable Size Automatic}.  The same advantages and limitations
450 of @code{strdupa} are valid for @code{strndupa}, too.
452 This function is implemented only as a macro, just like @code{strdupa}.
454 @code{strndupa} is only available if GNU CC is used.
455 @end deftypefn
457 @comment string.h
458 @comment ISO
459 @deftypefun {char *} strcat (char *@var{to}, const char *@var{from})
460 The @code{strcat} function is similar to @code{strcpy}, except that the
461 characters from @var{from} are concatenated or appended to the end of
462 @var{to}, instead of overwriting it.  That is, the first character from
463 @var{from} overwrites the null character marking the end of @var{to}.
465 An equivalent definition for @code{strcat} would be:
467 @smallexample
468 char *
469 strcat (char *to, const char *from)
471   strcpy (to + strlen (to), from);
472   return to;
474 @end smallexample
476 This function has undefined results if the strings overlap.
477 @end deftypefun
479 @comment string.h
480 @comment ISO
481 @deftypefun {char *} strncat (char *@var{to}, const char *@var{from}, size_t @var{size})
482 This function is like @code{strcat} except that not more than @var{size}
483 characters from @var{from} are appended to the end of @var{to}.  A
484 single null character is also always appended to @var{to}, so the total
485 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
486 longer than its initial length.
488 The @code{strncat} function could be implemented like this:
490 @smallexample
491 @group
492 char *
493 strncat (char *to, const char *from, size_t size)
495   strncpy (to + strlen (to), from, size);
496   return to;
498 @end group
499 @end smallexample
501 The behavior of @code{strncat} is undefined if the strings overlap.
502 @end deftypefun
504 Here is an example showing the use of @code{strncpy} and @code{strncat}.
505 Notice how, in the call to @code{strncat}, the @var{size} parameter
506 is computed to avoid overflowing the character array @code{buffer}.
508 @smallexample
509 @include strncat.c.texi
510 @end smallexample
512 @noindent
513 The output produced by this program looks like:
515 @smallexample
516 hello
517 hello, wo
518 @end smallexample
520 @comment string.h
521 @comment BSD
522 @deftypefun void bcopy (const void *@var{from}, void *@var{to}, size_t @var{size})
523 This is a partially obsolete alternative for @code{memmove}, derived from
524 BSD.  Note that it is not quite equivalent to @code{memmove}, because the
525 arguments are not in the same order and there is no return value.
526 @end deftypefun
528 @comment string.h
529 @comment BSD
530 @deftypefun void bzero (void *@var{block}, size_t @var{size})
531 This is a partially obsolete alternative for @code{memset}, derived from
532 BSD.  Note that it is not as general as @code{memset}, because the only
533 value it can store is zero.
534 @end deftypefun
536 @node String/Array Comparison
537 @section String/Array Comparison
538 @cindex comparing strings and arrays
539 @cindex string comparison functions
540 @cindex array comparison functions
541 @cindex predicates on strings
542 @cindex predicates on arrays
544 You can use the functions in this section to perform comparisons on the
545 contents of strings and arrays.  As well as checking for equality, these
546 functions can also be used as the ordering functions for sorting
547 operations.  @xref{Searching and Sorting}, for an example of this.
549 Unlike most comparison operations in C, the string comparison functions
550 return a nonzero value if the strings are @emph{not} equivalent rather
551 than if they are.  The sign of the value indicates the relative ordering
552 of the first characters in the strings that are not equivalent:  a
553 negative value indicates that the first string is ``less'' than the
554 second, while a positive value indicates that the first string is
555 ``greater''.
557 The most common use of these functions is to check only for equality.
558 This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
560 All of these functions are declared in the header file @file{string.h}.
561 @pindex string.h
563 @comment string.h
564 @comment ISO
565 @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
566 The function @code{memcmp} compares the @var{size} bytes of memory
567 beginning at @var{a1} against the @var{size} bytes of memory beginning
568 at @var{a2}.  The value returned has the same sign as the difference
569 between the first differing pair of bytes (interpreted as @code{unsigned
570 char} objects, then promoted to @code{int}).
572 If the contents of the two blocks are equal, @code{memcmp} returns
573 @code{0}.
574 @end deftypefun
576 On arbitrary arrays, the @code{memcmp} function is mostly useful for
577 testing equality.  It usually isn't meaningful to do byte-wise ordering
578 comparisons on arrays of things other than bytes.  For example, a
579 byte-wise comparison on the bytes that make up floating-point numbers
580 isn't likely to tell you anything about the relationship between the
581 values of the floating-point numbers.
583 You should also be careful about using @code{memcmp} to compare objects
584 that can contain ``holes'', such as the padding inserted into structure
585 objects to enforce alignment requirements, extra space at the end of
586 unions, and extra characters at the ends of strings whose length is less
587 than their allocated size.  The contents of these ``holes'' are
588 indeterminate and may cause strange behavior when performing byte-wise
589 comparisons.  For more predictable results, perform an explicit
590 component-wise comparison.
592 For example, given a structure type definition like:
594 @smallexample
595 struct foo
596   @{
597     unsigned char tag;
598     union
599       @{
600         double f;
601         long i;
602         char *p;
603       @} value;
604   @};
605 @end smallexample
607 @noindent
608 you are better off writing a specialized comparison function to compare
609 @code{struct foo} objects instead of comparing them with @code{memcmp}.
611 @comment string.h
612 @comment ISO
613 @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
614 The @code{strcmp} function compares the string @var{s1} against
615 @var{s2}, returning a value that has the same sign as the difference
616 between the first differing pair of characters (interpreted as
617 @code{unsigned char} objects, then promoted to @code{int}).
619 If the two strings are equal, @code{strcmp} returns @code{0}.
621 A consequence of the ordering used by @code{strcmp} is that if @var{s1}
622 is an initial substring of @var{s2}, then @var{s1} is considered to be
623 ``less than'' @var{s2}.
624 @end deftypefun
626 @comment string.h
627 @comment BSD
628 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
629 This function is like @code{strcmp}, except that differences in case are
630 ignored.  How uppercase and lowercase characters are related is
631 determined by the currently selected locale.  In the standard @code{"C"}
632 locale the characters @"A and @"a do not match but in a locale which
633 regards these characters as parts of the alphabet they do match.
635 @code{strcasecmp} is derived from BSD.
636 @end deftypefun
638 @comment string.h
639 @comment BSD
640 @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
641 This function is like @code{strncmp}, except that differences in case
642 are ignored.  Like @code{strcasecmp}, it is locale dependent how
643 uppercase and lowercase characters are related.
645 @code{strncasecmp} is a GNU extension.
646 @end deftypefun
648 @comment string.h
649 @comment ISO
650 @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
651 This function is the similar to @code{strcmp}, except that no more than
652 @var{size} characters are compared.  In other words, if the two strings are
653 the same in their first @var{size} characters, the return value is zero.
654 @end deftypefun
656 Here are some examples showing the use of @code{strcmp} and @code{strncmp}.
657 These examples assume the use of the ASCII character set.  (If some
658 other character set---say, EBCDIC---is used instead, then the glyphs
659 are associated with different numeric codes, and the return values
660 and ordering may differ.)
662 @smallexample
663 strcmp ("hello", "hello")
664     @result{} 0    /* @r{These two strings are the same.} */
665 strcmp ("hello", "Hello")
666     @result{} 32   /* @r{Comparisons are case-sensitive.} */
667 strcmp ("hello", "world")
668     @result{} -15  /* @r{The character @code{'h'} comes before @code{'w'}.} */
669 strcmp ("hello", "hello, world")
670     @result{} -44  /* @r{Comparing a null character against a comma.} */
671 strncmp ("hello", "hello, world", 5)
672     @result{} 0    /* @r{The initial 5 characters are the same.} */
673 strncmp ("hello, world", "hello, stupid world!!!", 5)
674     @result{} 0    /* @r{The initial 5 characters are the same.} */
675 @end smallexample
677 @comment string.h
678 @comment GNU
679 @deftypefun int strverscmp (const char *@var{s1}, const char *@var{s2})
680 The @code{strverscmp} function compares the string @var{s1} against
681 @var{s2}, considering them as holding indices/version numbers.  Return
682 value follows the same conventions as found in the @code{strverscmp}
683 function.  In fact, if @var{s1} and @var{s2} contain no digits,
684 @code{strverscmp} behaves like @code{strcmp}.
686 Basically, we compare strings normally (character by character), until
687 we find a digit in each string - then we enter a special comparison
688 mode, where each sequence of digits is taken as a whole.  If we reach the
689 end of these two parts without noticing a difference, we return to the
690 standard comparison mode.  There are two types of numeric parts:
691 "integral" and "fractional" (those  begin with a '0'). The types
692 of the numeric parts affect the way we sort them:
694 @itemize @bullet
695 @item
696 integral/integral: we compare values as you would expect.
698 @item
699 fractional/integral: the fractional part is less than the integral one.
700 Again, no surprise.
702 @item
703 fractional/fractional: the things become a bit more complex.
704 If the common prefix contains only leading zeroes, the longest part is less
705 than the other one; else the comparison behaves normally.
706 @end itemize
708 @smallexample
709 strverscmp ("no digit", "no digit")
710     @result{} 0    /* @r{same behaviour as strcmp.} */
711 strverscmp ("item#99", "item#100")
712     @result{} <0   /* @r{same prefix, but 99 < 100.} */
713 strverscmp ("alpha1", "alpha001")
714     @result{} >0   /* @r{fractional part inferior to integral one.} */
715 strverscmp ("part1_f012", "part1_f01")
716     @result{} >0   /* @r{two fractional parts.} */
717 strverscmp ("foo.009", "foo.0")
718     @result{} <0   /* @r{idem, but with leading zeroes only.} */
719 @end smallexample
721 This function is especially useful when dealing with filename sorting,
722 because filenames frequently hold indices/version numbers.
724 @code{strverscmp} is a GNU extension.
725 @end deftypefun
727 @comment string.h
728 @comment BSD
729 @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
730 This is an obsolete alias for @code{memcmp}, derived from BSD.
731 @end deftypefun
733 @node Collation Functions
734 @section Collation Functions
736 @cindex collating strings
737 @cindex string collation functions
739 In some locales, the conventions for lexicographic ordering differ from
740 the strict numeric ordering of character codes.  For example, in Spanish
741 most glyphs with diacritical marks such as accents are not considered
742 distinct letters for the purposes of collation.  On the other hand, the
743 two-character sequence @samp{ll} is treated as a single letter that is
744 collated immediately after @samp{l}.
746 You can use the functions @code{strcoll} and @code{strxfrm} (declared in
747 the header file @file{string.h}) to compare strings using a collation
748 ordering appropriate for the current locale.  The locale used by these
749 functions in particular can be specified by setting the locale for the
750 @code{LC_COLLATE} category; see @ref{Locales}.
751 @pindex string.h
753 In the standard C locale, the collation sequence for @code{strcoll} is
754 the same as that for @code{strcmp}.
756 Effectively, the way these functions work is by applying a mapping to
757 transform the characters in a string to a byte sequence that represents
758 the string's position in the collating sequence of the current locale.
759 Comparing two such byte sequences in a simple fashion is equivalent to
760 comparing the strings with the locale's collating sequence.
762 The function @code{strcoll} performs this translation implicitly, in
763 order to do one comparison.  By contrast, @code{strxfrm} performs the
764 mapping explicitly.  If you are making multiple comparisons using the
765 same string or set of strings, it is likely to be more efficient to use
766 @code{strxfrm} to transform all the strings just once, and subsequently
767 compare the transformed strings with @code{strcmp}.
769 @comment string.h
770 @comment ISO
771 @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
772 The @code{strcoll} function is similar to @code{strcmp} but uses the
773 collating sequence of the current locale for collation (the
774 @code{LC_COLLATE} locale).
775 @end deftypefun
777 Here is an example of sorting an array of strings, using @code{strcoll}
778 to compare them.  The actual sort algorithm is not written here; it
779 comes from @code{qsort} (@pxref{Array Sort Function}).  The job of the
780 code shown here is to say how to compare the strings while sorting them.
781 (Later on in this section, we will show a way to do this more
782 efficiently using @code{strxfrm}.)
784 @smallexample
785 /* @r{This is the comparison function used with @code{qsort}.} */
788 compare_elements (char **p1, char **p2)
790   return strcoll (*p1, *p2);
793 /* @r{This is the entry point---the function to sort}
794    @r{strings using the locale's collating sequence.} */
796 void
797 sort_strings (char **array, int nstrings)
799   /* @r{Sort @code{temp_array} by comparing the strings.} */
800   qsort (array, sizeof (char *),
801          nstrings, compare_elements);
803 @end smallexample
805 @cindex converting string to collation order
806 @comment string.h
807 @comment ISO
808 @deftypefun size_t strxfrm (char *@var{to}, const char *@var{from}, size_t @var{size})
809 The function @code{strxfrm} transforms @var{string} using the collation
810 transformation determined by the locale currently selected for
811 collation, and stores the transformed string in the array @var{to}.  Up
812 to @var{size} characters (including a terminating null character) are
813 stored.
815 The behavior is undefined if the strings @var{to} and @var{from}
816 overlap; see @ref{Copying and Concatenation}.
818 The return value is the length of the entire transformed string.  This
819 value is not affected by the value of @var{size}, but if it is greater
820 or equal than @var{size}, it means that the transformed string did not
821 entirely fit in the array @var{to}.  In this case, only as much of the
822 string as actually fits was stored.  To get the whole transformed
823 string, call @code{strxfrm} again with a bigger output array.
825 The transformed string may be longer than the original string, and it
826 may also be shorter.
828 If @var{size} is zero, no characters are stored in @var{to}.  In this
829 case, @code{strxfrm} simply returns the number of characters that would
830 be the length of the transformed string.  This is useful for determining
831 what size string to allocate.  It does not matter what @var{to} is if
832 @var{size} is zero; @var{to} may even be a null pointer.
833 @end deftypefun
835 Here is an example of how you can use @code{strxfrm} when
836 you plan to do many comparisons.  It does the same thing as the previous
837 example, but much faster, because it has to transform each string only
838 once, no matter how many times it is compared with other strings.  Even
839 the time needed to allocate and free storage is much less than the time
840 we save, when there are many strings.
842 @smallexample
843 struct sorter @{ char *input; char *transformed; @};
845 /* @r{This is the comparison function used with @code{qsort}}
846    @r{to sort an array of @code{struct sorter}.} */
849 compare_elements (struct sorter *p1, struct sorter *p2)
851   return strcmp (p1->transformed, p2->transformed);
854 /* @r{This is the entry point---the function to sort}
855    @r{strings using the locale's collating sequence.} */
857 void
858 sort_strings_fast (char **array, int nstrings)
860   struct sorter temp_array[nstrings];
861   int i;
863   /* @r{Set up @code{temp_array}.  Each element contains}
864      @r{one input string and its transformed string.} */
865   for (i = 0; i < nstrings; i++)
866     @{
867       size_t length = strlen (array[i]) * 2;
868       char *transformed;
869       size_t transformed_length;
871       temp_array[i].input = array[i];
873       /* @r{First try a buffer perhaps big enough.}  */
874       transformed = (char *) xmalloc (length);
876       /* @r{Transform @code{array[i]}.}  */
877       transformed_length = strxfrm (transformed, array[i], length);
879       /* @r{If the buffer was not large enough, resize it}
880          @r{and try again.}  */
881       if (transformed_length >= length)
882         @{
883           /* @r{Allocate the needed space. +1 for terminating}
884              @r{@code{NUL} character.}  */
885           transformed = (char *) xrealloc (transformed,
886                                            transformed_length + 1);
888           /* @r{The return value is not interesting because we know}
889              @r{how long the transformed string is.}  */
890           (void) strxfrm (transformed, array[i],
891                           transformed_length + 1);
892         @}
894       temp_array[i].transformed = transformed;
895     @}
897   /* @r{Sort @code{temp_array} by comparing transformed strings.} */
898   qsort (temp_array, sizeof (struct sorter),
899          nstrings, compare_elements);
901   /* @r{Put the elements back in the permanent array}
902      @r{in their sorted order.} */
903   for (i = 0; i < nstrings; i++)
904     array[i] = temp_array[i].input;
906   /* @r{Free the strings we allocated.} */
907   for (i = 0; i < nstrings; i++)
908     free (temp_array[i].transformed);
910 @end smallexample
912 @strong{Compatibility Note:}  The string collation functions are a new
913 feature of @w{ISO C 89}.  Older C dialects have no equivalent feature.
915 @node Search Functions
916 @section Search Functions
918 This section describes library functions which perform various kinds
919 of searching operations on strings and arrays.  These functions are
920 declared in the header file @file{string.h}.
921 @pindex string.h
922 @cindex search functions (for strings)
923 @cindex string search functions
925 @comment string.h
926 @comment ISO
927 @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
928 This function finds the first occurrence of the byte @var{c} (converted
929 to an @code{unsigned char}) in the initial @var{size} bytes of the
930 object beginning at @var{block}.  The return value is a pointer to the
931 located byte, or a null pointer if no match was found.
932 @end deftypefun
934 @comment string.h
935 @comment ISO
936 @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
937 The @code{strchr} function finds the first occurrence of the character
938 @var{c} (converted to a @code{char}) in the null-terminated string
939 beginning at @var{string}.  The return value is a pointer to the located
940 character, or a null pointer if no match was found.
942 For example,
943 @smallexample
944 strchr ("hello, world", 'l')
945     @result{} "llo, world"
946 strchr ("hello, world", '?')
947     @result{} NULL
948 @end smallexample
950 The terminating null character is considered to be part of the string,
951 so you can use this function get a pointer to the end of a string by
952 specifying a null character as the value of the @var{c} argument.
953 @end deftypefun
955 @comment string.h
956 @comment BSD
957 @deftypefun {char *} index (const char *@var{string}, int @var{c})
958 @code{index} is another name for @code{strchr}; they are exactly the same.
959 New code should always use @code{strchr} since this name is defined in
960 @w{ISO C} while @code{index} is a BSD invention which never was available
961 on @w{System V} derived systems.
962 @end deftypefun
964 @comment string.h
965 @comment ISO
966 @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
967 The function @code{strrchr} is like @code{strchr}, except that it searches
968 backwards from the end of the string @var{string} (instead of forwards
969 from the front).
971 For example,
972 @smallexample
973 strrchr ("hello, world", 'l')
974     @result{} "ld"
975 @end smallexample
976 @end deftypefun
978 @comment string.h
979 @comment BSD
980 @deftypefun {char *} rindex (const char *@var{string}, int @var{c})
981 @code{rindex} is another name for @code{strrchr}; they are exactly the same.
982 New code should always use @code{strrchr} since this name is defined in
983 @w{ISO C} while @code{rindex} is a BSD invention which never was available
984 on @w{System V} derived systems.
985 @end deftypefun
987 @comment string.h
988 @comment ISO
989 @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
990 This is like @code{strchr}, except that it searches @var{haystack} for a
991 substring @var{needle} rather than just a single character.  It
992 returns a pointer into the string @var{haystack} that is the first
993 character of the substring, or a null pointer if no match was found.  If
994 @var{needle} is an empty string, the function returns @var{haystack}.
996 For example,
997 @smallexample
998 strstr ("hello, world", "l")
999     @result{} "llo, world"
1000 strstr ("hello, world", "wo")
1001     @result{} "world"
1002 @end smallexample
1003 @end deftypefun
1006 @comment string.h
1007 @comment GNU
1008 @deftypefun {void *} memmem (const void *@var{haystack}, size_t @var{haystack-len},@*const void *@var{needle}, size_t @var{needle-len})
1009 This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
1010 arrays rather than null-terminated strings.  @var{needle-len} is the
1011 length of @var{needle} and @var{haystack-len} is the length of
1012 @var{haystack}.@refill
1014 This function is a GNU extension.
1015 @end deftypefun
1017 @comment string.h
1018 @comment ISO
1019 @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
1020 The @code{strspn} (``string span'') function returns the length of the
1021 initial substring of @var{string} that consists entirely of characters that
1022 are members of the set specified by the string @var{skipset}.  The order
1023 of the characters in @var{skipset} is not important.
1025 For example,
1026 @smallexample
1027 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
1028     @result{} 5
1029 @end smallexample
1030 @end deftypefun
1032 @comment string.h
1033 @comment ISO
1034 @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
1035 The @code{strcspn} (``string complement span'') function returns the length
1036 of the initial substring of @var{string} that consists entirely of characters
1037 that are @emph{not} members of the set specified by the string @var{stopset}.
1038 (In other words, it returns the offset of the first character in @var{string}
1039 that is a member of the set @var{stopset}.)
1041 For example,
1042 @smallexample
1043 strcspn ("hello, world", " \t\n,.;!?")
1044     @result{} 5
1045 @end smallexample
1046 @end deftypefun
1048 @comment string.h
1049 @comment ISO
1050 @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
1051 The @code{strpbrk} (``string pointer break'') function is related to
1052 @code{strcspn}, except that it returns a pointer to the first character
1053 in @var{string} that is a member of the set @var{stopset} instead of the
1054 length of the initial substring.  It returns a null pointer if no such
1055 character from @var{stopset} is found.
1057 @c @group  Invalid outside the example.
1058 For example,
1060 @smallexample
1061 strpbrk ("hello, world", " \t\n,.;!?")
1062     @result{} ", world"
1063 @end smallexample
1064 @c @end group
1065 @end deftypefun
1067 @node Finding Tokens in a String
1068 @section Finding Tokens in a String
1070 @cindex tokenizing strings
1071 @cindex breaking a string into tokens
1072 @cindex parsing tokens from a string
1073 It's fairly common for programs to have a need to do some simple kinds
1074 of lexical analysis and parsing, such as splitting a command string up
1075 into tokens.  You can do this with the @code{strtok} function, declared
1076 in the header file @file{string.h}.
1077 @pindex string.h
1079 @comment string.h
1080 @comment ISO
1081 @deftypefun {char *} strtok (char *@var{newstring}, const char *@var{delimiters})
1082 A string can be split into tokens by making a series of calls to the
1083 function @code{strtok}.
1085 The string to be split up is passed as the @var{newstring} argument on
1086 the first call only.  The @code{strtok} function uses this to set up
1087 some internal state information.  Subsequent calls to get additional
1088 tokens from the same string are indicated by passing a null pointer as
1089 the @var{newstring} argument.  Calling @code{strtok} with another
1090 non-null @var{newstring} argument reinitializes the state information.
1091 It is guaranteed that no other library function ever calls @code{strtok}
1092 behind your back (which would mess up this internal state information).
1094 The @var{delimiters} argument is a string that specifies a set of delimiters
1095 that may surround the token being extracted.  All the initial characters
1096 that are members of this set are discarded.  The first character that is
1097 @emph{not} a member of this set of delimiters marks the beginning of the
1098 next token.  The end of the token is found by looking for the next
1099 character that is a member of the delimiter set.  This character in the
1100 original string @var{newstring} is overwritten by a null character, and the
1101 pointer to the beginning of the token in @var{newstring} is returned.
1103 On the next call to @code{strtok}, the searching begins at the next
1104 character beyond the one that marked the end of the previous token.
1105 Note that the set of delimiters @var{delimiters} do not have to be the
1106 same on every call in a series of calls to @code{strtok}.
1108 If the end of the string @var{newstring} is reached, or if the remainder of
1109 string consists only of delimiter characters, @code{strtok} returns
1110 a null pointer.
1111 @end deftypefun
1113 @strong{Warning:} Since @code{strtok} alters the string it is parsing,
1114 you should always copy the string to a temporary buffer before parsing
1115 it with @code{strtok}.  If you allow @code{strtok} to modify a string
1116 that came from another part of your program, you are asking for trouble;
1117 that string might be used for other purposes after @code{strtok} has
1118 modified it, and it would not have the expected value.
1120 The string that you are operating on might even be a constant.  Then
1121 when @code{strtok} tries to modify it, your program will get a fatal
1122 signal for writing in read-only memory.  @xref{Program Error Signals}.
1124 This is a special case of a general principle: if a part of a program
1125 does not have as its purpose the modification of a certain data
1126 structure, then it is error-prone to modify the data structure
1127 temporarily.
1129 The function @code{strtok} is not reentrant.  @xref{Nonreentrancy}, for
1130 a discussion of where and why reentrancy is important.
1132 Here is a simple example showing the use of @code{strtok}.
1134 @comment Yes, this example has been tested.
1135 @smallexample
1136 #include <string.h>
1137 #include <stddef.h>
1139 @dots{}
1141 const char string[] = "words separated by spaces -- and, punctuation!";
1142 const char delimiters[] = " .,;:!-";
1143 char *token, *cp;
1145 @dots{}
1147 cp = strdupa (string);                /* Make writable copy.  */
1148 token = strtok (cp, delimiters);      /* token => "words" */
1149 token = strtok (NULL, delimiters);    /* token => "separated" */
1150 token = strtok (NULL, delimiters);    /* token => "by" */
1151 token = strtok (NULL, delimiters);    /* token => "spaces" */
1152 token = strtok (NULL, delimiters);    /* token => "and" */
1153 token = strtok (NULL, delimiters);    /* token => "punctuation" */
1154 token = strtok (NULL, delimiters);    /* token => NULL */
1155 @end smallexample
1157 The GNU C library contains two more functions for tokenizing a string
1158 which overcome the limitation of non-reentrancy.
1160 @comment string.h
1161 @comment POSIX
1162 @deftypefun {char *} strtok_r (char *@var{newstring}, const char *@var{delimiters}, char **@var{save_ptr})
1163 Just like @code{strtok}, this function splits the string into several
1164 tokens which can be accessed by successive calls to @code{strtok_r}.
1165 The difference is that the information about the next token is stored in
1166 the space pointed to by the third argument, @var{save_ptr}, which is a
1167 pointer to a string pointer.  Calling @code{strtok_r} with a null
1168 pointer for @var{newstring} and leaving @var{save_ptr} between the calls
1169 unchanged does the job without hindering reentrancy.
1171 This function is defined in POSIX-1 and can be found on many systems
1172 which support multi-threading.
1173 @end deftypefun
1175 @comment string.h
1176 @comment BSD
1177 @deftypefun {char *} strsep (char **@var{string_ptr}, const char *@var{delimiter})
1178 This function is just @code{strtok_r} with the @var{newstring} argument
1179 replaced by the @var{save_ptr} argument.  The initialization of the
1180 moving pointer has to be done by the user.  Successive calls to
1181 @code{strsep} move the pointer along the tokens separated by
1182 @var{delimiter}, returning the address of the next token and updating
1183 @var{string_ptr} to point to the beginning of the next token.
1185 If the input string contains more than one character from
1186 @var{delimiter} in a row @code{strsep} returns an empty string for each
1187 pair of characters from @var{delimiter}.  This means that a program
1188 normally should test for @code{strsep} returning an empty string before
1189 processing it.
1191 This function was introduced in 4.3BSD and therefore is widely available.
1192 @end deftypefun
1194 Here is how the above example looks like when @code{strsep} is used.
1196 @comment Yes, this example has been tested.
1197 @smallexample
1198 #include <string.h>
1199 #include <stddef.h>
1201 @dots{}
1203 const char string[] = "words separated by spaces -- and, punctuation!";
1204 const char delimiters[] = " .,;:!-";
1205 char *running;
1206 char *token;
1208 @dots{}
1210 running = strdupa (string);
1211 token = strsep (&running, delimiters);    /* token => "words" */
1212 token = strsep (&running, delimiters);    /* token => "separated" */
1213 token = strsep (&running, delimiters);    /* token => "by" */
1214 token = strsep (&running, delimiters);    /* token => "spaces" */
1215 token = strsep (&running, delimiters);    /* token => "" */
1216 token = strsep (&running, delimiters);    /* token => "" */
1217 token = strsep (&running, delimiters);    /* token => "" */
1218 token = strsep (&running, delimiters);    /* token => "and" */
1219 token = strsep (&running, delimiters);    /* token => "" */
1220 token = strsep (&running, delimiters);    /* token => "punctuation" */
1221 token = strsep (&running, delimiters);    /* token => "" */
1222 token = strsep (&running, delimiters);    /* token => NULL */
1223 @end smallexample
1225 @node Encode Binary Data
1226 @section Encode Binary Data
1228 To store or transfer binary data in environments which only support text
1229 one has to encode the binary data by mapping the input bytes to
1230 characters in the range allowed for storing or transfering.  SVID
1231 systems (and nowadays XPG compliant systems) provide minimal support for
1232 this task.
1234 @comment stdlib.h
1235 @comment XPG
1236 @deftypefun {char *} l64a (long int @var{n})
1237 This function encodes a 32-bit input value using characters from the
1238 basic character set.  It returns a pointer to a 6 character buffer which
1239 contains an encoded version of @var{n}.  To encode a series of bytes the
1240 user must copy the returned string to a destination buffer.  It returns
1241 the empty string if @var{n} is zero, which is somewhat bizarre but
1242 mandated by the standard.@*
1243 @strong{Warning:} Since a static buffer is used this function should not
1244 be used in multi-threaded programs.  There is no thread-safe alternative
1245 to this function in the C library.@*
1246 @strong{Compatibility Note:} The XPG standard states that the return
1247 value of @code{l64a} is undefined if @var{n} is negative.  In the GNU
1248 implementation, @code{l64a} treats its argument as unsigned, so it will
1249 return a sensible encoding for any nonzero @var{n}; however, portable
1250 programs should not rely on this.
1252 To encode a large buffer @code{l64a} must be called in a loop, once for
1253 each 32-bit word of the buffer.  For example, one could do something
1254 like this:
1256 @smallexample
1257 char *
1258 encode (const void *buf, size_t len)
1260   /* @r{We know in advance how long the buffer has to be.} */
1261   unsigned char *in = (unsigned char *) buf;
1262   char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
1263   char *cp = out;
1265   /* @r{Encode the length.} */
1266   /* @r{Using `htonl' is necessary so that the data can be}
1267      @r{decoded even on machines with different byte order.} */
1269   cp = mempcpy (cp, l64a (htonl (len)), 6);
1271   while (len > 3)
1272     @{
1273       unsigned long int n = *in++;
1274       n = (n << 8) | *in++;
1275       n = (n << 8) | *in++;
1276       n = (n << 8) | *in++;
1277       len -= 4;
1278       if (n)
1279         cp = mempcpy (cp, l64a (htonl (n)), 6);
1280       else
1281             /* @r{`l64a' returns the empty string for n==0, so we }
1282                @r{must generate its encoding (}"......"@r{) by hand.} */
1283         cp = stpcpy (cp, "......");
1284     @}
1285   if (len > 0)
1286     @{
1287       unsigned long int n = *in++;
1288       if (--len > 0)
1289         @{
1290           n = (n << 8) | *in++;
1291           if (--len > 0)
1292             n = (n << 8) | *in;
1293         @}
1294       memcpy (cp, l64a (htonl (n)), 6);
1295       cp += 6;
1296     @}
1297   *cp = '\0';
1298   return out;
1300 @end smallexample
1302 It is strange that the library does not provide the complete
1303 functionality needed but so be it.
1305 @end deftypefun
1307 To decode data produced with @code{l64a} the following function should be
1308 used.
1310 @comment stdlib.h
1311 @comment XPG
1312 @deftypefun {long int} a64l (const char *@var{string})
1313 The parameter @var{string} should contain a string which was produced by
1314 a call to @code{l64a}.  The function processes at least 6 characters of
1315 this string, and decodes the characters it finds according to the table
1316 below.  It stops decoding when it finds a character not in the table,
1317 rather like @code{atoi}; if you have a buffer which has been broken into
1318 lines, you must be careful to skip over the end-of-line characters.
1320 The decoded number is returned as a @code{long int} value.
1321 @end deftypefun
1323 The @code{l64a} and @code{a64l} functions use a base 64 encoding, in
1324 which each character of an encoded string represents six bits of an
1325 input word.  These symbols are used for the base 64 digits:
1327 @multitable {xxxxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx}
1328 @item              @tab 0 @tab 1 @tab 2 @tab 3 @tab 4 @tab 5 @tab 6 @tab 7
1329 @item       0      @tab @code{.} @tab @code{/} @tab @code{0} @tab @code{1}
1330                    @tab @code{2} @tab @code{3} @tab @code{4} @tab @code{5}
1331 @item       8      @tab @code{6} @tab @code{7} @tab @code{8} @tab @code{9}
1332                    @tab @code{A} @tab @code{B} @tab @code{C} @tab @code{D}
1333 @item       16     @tab @code{E} @tab @code{F} @tab @code{G} @tab @code{H}
1334                    @tab @code{I} @tab @code{J} @tab @code{K} @tab @code{L}
1335 @item       24     @tab @code{M} @tab @code{N} @tab @code{O} @tab @code{P}
1336                    @tab @code{Q} @tab @code{R} @tab @code{S} @tab @code{T}
1337 @item       32     @tab @code{U} @tab @code{V} @tab @code{W} @tab @code{X}
1338                    @tab @code{Y} @tab @code{Z} @tab @code{a} @tab @code{b}
1339 @item       40     @tab @code{c} @tab @code{d} @tab @code{e} @tab @code{f}
1340                    @tab @code{g} @tab @code{h} @tab @code{i} @tab @code{j}
1341 @item       48     @tab @code{k} @tab @code{l} @tab @code{m} @tab @code{n}
1342                    @tab @code{o} @tab @code{p} @tab @code{q} @tab @code{r}
1343 @item       56     @tab @code{s} @tab @code{t} @tab @code{u} @tab @code{v}
1344                    @tab @code{w} @tab @code{x} @tab @code{y} @tab @code{z}
1345 @end multitable
1347 This encoding scheme is not standard.  There are some other encoding
1348 methods which are much more widely used (UU encoding, MIME encoding).
1349 Generally, it is better to use one of these encodings.
1351 @node Argz and Envz Vectors
1352 @section Argz and Envz Vectors
1354 @cindex argz vectors (string vectors)
1355 @cindex string vectors, null-character separated
1356 @cindex argument vectors, null-character separated
1357 @dfn{argz vectors} are vectors of strings in a contiguous block of
1358 memory, each element separated from its neighbors by null-characters
1359 (@code{'\0'}).
1361 @cindex envz vectors (environment vectors)
1362 @cindex environment vectors, null-character separated
1363 @dfn{Envz vectors} are an extension of argz vectors where each element is a
1364 name-value pair, separated by a @code{'='} character (as in a Unix
1365 environment).
1367 @menu
1368 * Argz Functions::              Operations on argz vectors.
1369 * Envz Functions::              Additional operations on environment vectors.
1370 @end menu
1372 @node Argz Functions, Envz Functions, , Argz and Envz Vectors
1373 @subsection Argz Functions
1375 Each argz vector is represented by a pointer to the first element, of
1376 type @code{char *}, and a size, of type @code{size_t}, both of which can
1377 be initialized to @code{0} to represent an empty argz vector.  All argz
1378 functions accept either a pointer and a size argument, or pointers to
1379 them, if they will be modified.
1381 The argz functions use @code{malloc}/@code{realloc} to allocate/grow
1382 argz vectors, and so any argz vector creating using these functions may
1383 be freed by using @code{free}; conversely, any argz function that may
1384 grow a string expects that string to have been allocated using
1385 @code{malloc} (those argz functions that only examine their arguments or
1386 modify them in place will work on any sort of memory).
1387 @xref{Unconstrained Allocation}.
1389 All argz functions that do memory allocation have a return type of
1390 @code{error_t}, and return @code{0} for success, and @code{ENOMEM} if an
1391 allocation error occurs.
1393 @pindex argz.h
1394 These functions are declared in the standard include file @file{argz.h}.
1396 @comment argz.h
1397 @comment GNU
1398 @deftypefun {error_t} argz_create (char *const @var{argv}[], char **@var{argz}, size_t *@var{argz_len})
1399 The @code{argz_create} function converts the Unix-style argument vector
1400 @var{argv} (a vector of pointers to normal C strings, terminated by
1401 @code{(char *)0}; @pxref{Program Arguments}) into an argz vector with
1402 the same elements, which is returned in @var{argz} and @var{argz_len}.
1403 @end deftypefun
1405 @comment argz.h
1406 @comment GNU
1407 @deftypefun {error_t} argz_create_sep (const char *@var{string}, int @var{sep}, char **@var{argz}, size_t *@var{argz_len})
1408 The @code{argz_create_sep} function converts the null-terminated string
1409 @var{string} into an argz vector (returned in @var{argz} and
1410 @var{argz_len}) by splitting it into elements at every occurance of the
1411 character @var{sep}.
1412 @end deftypefun
1414 @comment argz.h
1415 @comment GNU
1416 @deftypefun {size_t} argz_count (const char *@var{argz}, size_t @var{arg_len})
1417 Returns the number of elements in the argz vector @var{argz} and
1418 @var{argz_len}.
1419 @end deftypefun
1421 @comment argz.h
1422 @comment GNU
1423 @deftypefun {void} argz_extract (char *@var{argz}, size_t @var{argz_len}, char **@var{argv})
1424 The @code{argz_extract} function converts the argz vector @var{argz} and
1425 @var{argz_len} into a Unix-style argument vector stored in @var{argv},
1426 by putting pointers to every element in @var{argz} into successive
1427 positions in @var{argv}, followed by a terminator of @code{0}.
1428 @var{Argv} must be pre-allocated with enough space to hold all the
1429 elements in @var{argz} plus the terminating @code{(char *)0}
1430 (@code{(argz_count (@var{argz}, @var{argz_len}) + 1) * sizeof (char *)}
1431 bytes should be enough).  Note that the string pointers stored into
1432 @var{argv} point into @var{argz}---they are not copies---and so
1433 @var{argz} must be copied if it will be changed while @var{argv} is
1434 still active.  This function is useful for passing the elements in
1435 @var{argz} to an exec function (@pxref{Executing a File}).
1436 @end deftypefun
1438 @comment argz.h
1439 @comment GNU
1440 @deftypefun {void} argz_stringify (char *@var{argz}, size_t @var{len}, int @var{sep})
1441 The @code{argz_stringify} converts @var{argz} into a normal string with
1442 the elements separated by the character @var{sep}, by replacing each
1443 @code{'\0'} inside @var{argz} (except the last one, which terminates the
1444 string) with @var{sep}.  This is handy for printing @var{argz} in a
1445 readable manner.
1446 @end deftypefun
1448 @comment argz.h
1449 @comment GNU
1450 @deftypefun {error_t} argz_add (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str})
1451 The @code{argz_add} function adds the string @var{str} to the end of the
1452 argz vector @code{*@var{argz}}, and updates @code{*@var{argz}} and
1453 @code{*@var{argz_len}} accordingly.
1454 @end deftypefun
1456 @comment argz.h
1457 @comment GNU
1458 @deftypefun {error_t} argz_add_sep (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str}, int @var{delim})
1459 The @code{argz_add_sep} function is similar to @code{argz_add}, but
1460 @var{str} is split into separate elements in the result at occurances of
1461 the character @var{delim}.  This is useful, for instance, for
1462 adding the components of a Unix search path to an argz vector, by using
1463 a value of @code{':'} for @var{delim}.
1464 @end deftypefun
1466 @comment argz.h
1467 @comment GNU
1468 @deftypefun {error_t} argz_append (char **@var{argz}, size_t *@var{argz_len}, const char *@var{buf}, size_t @var{buf_len})
1469 The @code{argz_append} function appends @var{buf_len} bytes starting at
1470 @var{buf} to the argz vector @code{*@var{argz}}, reallocating
1471 @code{*@var{argz}} to accommodate it, and adding @var{buf_len} to
1472 @code{*@var{argz_len}}.
1473 @end deftypefun
1475 @comment argz.h
1476 @comment GNU
1477 @deftypefun {error_t} argz_delete (char **@var{argz}, size_t *@var{argz_len}, char *@var{entry})
1478 If @var{entry} points to the beginning of one of the elements in the
1479 argz vector @code{*@var{argz}}, the @code{argz_delete} function will
1480 remove this entry and reallocate @code{*@var{argz}}, modifying
1481 @code{*@var{argz}} and @code{*@var{argz_len}} accordingly.  Note that as
1482 destructive argz functions usually reallocate their argz argument,
1483 pointers into argz vectors such as @var{entry} will then become invalid.
1484 @end deftypefun
1486 @comment argz.h
1487 @comment GNU
1488 @deftypefun {error_t} argz_insert (char **@var{argz}, size_t *@var{argz_len}, char *@var{before}, const char *@var{entry})
1489 The @code{argz_insert} function inserts the string @var{entry} into the
1490 argz vector @code{*@var{argz}} at a point just before the existing
1491 element pointed to by @var{before}, reallocating @code{*@var{argz}} and
1492 updating @code{*@var{argz}} and @code{*@var{argz_len}}.  If @var{before}
1493 is @code{0}, @var{entry} is added to the end instead (as if by
1494 @code{argz_add}).  Since the first element is in fact the same as
1495 @code{*@var{argz}}, passing in @code{*@var{argz}} as the value of
1496 @var{before} will result in @var{entry} being inserted at the beginning.
1497 @end deftypefun
1499 @comment argz.h
1500 @comment GNU
1501 @deftypefun {char *} argz_next (char *@var{argz}, size_t @var{argz_len}, const char *@var{entry})
1502 The @code{argz_next} function provides a convenient way of iterating
1503 over the elements in the argz vector @var{argz}.  It returns a pointer
1504 to the next element in @var{argz} after the element @var{entry}, or
1505 @code{0} if there are no elements following @var{entry}.  If @var{entry}
1506 is @code{0}, the first element of @var{argz} is returned.
1508 This behavior suggests two styles of iteration:
1510 @smallexample
1511     char *entry = 0;
1512     while ((entry = argz_next (@var{argz}, @var{argz_len}, entry)))
1513       @var{action};
1514 @end smallexample
1516 (the double parentheses are necessary to make some C compilers shut up
1517 about what they consider a questionable @code{while}-test) and:
1519 @smallexample
1520     char *entry;
1521     for (entry = @var{argz};
1522          entry;
1523          entry = argz_next (@var{argz}, @var{argz_len}, entry))
1524       @var{action};
1525 @end smallexample
1527 Note that the latter depends on @var{argz} having a value of @code{0} if
1528 it is empty (rather than a pointer to an empty block of memory); this
1529 invariant is maintained for argz vectors created by the functions here.
1530 @end deftypefun
1532 @comment argz.h
1533 @comment GNU
1534 @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}})
1535 Replace any occurances of the string @var{str} in @var{argz} with
1536 @var{with}, reallocating @var{argz} as necessary.  If
1537 @var{replace_count} is non-zero, @code{*@var{replace_count}} will be
1538 incremented by number of replacements performed.
1539 @end deftypefun
1541 @node Envz Functions, , Argz Functions, Argz and Envz Vectors
1542 @subsection Envz Functions
1544 Envz vectors are just argz vectors with additional constraints on the form
1545 of each element; as such, argz functions can also be used on them, where it
1546 makes sense.
1548 Each element in an envz vector is a name-value pair, separated by a @code{'='}
1549 character; if multiple @code{'='} characters are present in an element, those
1550 after the first are considered part of the value, and treated like all other
1551 non-@code{'\0'} characters.
1553 If @emph{no} @code{'='} characters are present in an element, that element is
1554 considered the name of a ``null'' entry, as distinct from an entry with an
1555 empty value: @code{envz_get} will return @code{0} if given the name of null
1556 entry, whereas an entry with an empty value would result in a value of
1557 @code{""}; @code{envz_entry} will still find such entries, however.  Null
1558 entries can be removed with @code{envz_strip} function.
1560 As with argz functions, envz functions that may allocate memory (and thus
1561 fail) have a return type of @code{error_t}, and return either @code{0} or
1562 @code{ENOMEM}.
1564 @pindex envz.h
1565 These functions are declared in the standard include file @file{envz.h}.
1567 @comment envz.h
1568 @comment GNU
1569 @deftypefun {char *} envz_entry (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
1570 The @code{envz_entry} function finds the entry in @var{envz} with the name
1571 @var{name}, and returns a pointer to the whole entry---that is, the argz
1572 element which begins with @var{name} followed by a @code{'='} character.  If
1573 there is no entry with that name, @code{0} is returned.
1574 @end deftypefun
1576 @comment envz.h
1577 @comment GNU
1578 @deftypefun {char *} envz_get (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
1579 The @code{envz_get} function finds the entry in @var{envz} with the name
1580 @var{name} (like @code{envz_entry}), and returns a pointer to the value
1581 portion of that entry (following the @code{'='}).  If there is no entry with
1582 that name (or only a null entry), @code{0} is returned.
1583 @end deftypefun
1585 @comment envz.h
1586 @comment GNU
1587 @deftypefun {error_t} envz_add (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name}, const char *@var{value})
1588 The @code{envz_add} function adds an entry to @code{*@var{envz}}
1589 (updating @code{*@var{envz}} and @code{*@var{envz_len}}) with the name
1590 @var{name}, and value @var{value}.  If an entry with the same name
1591 already exists in @var{envz}, it is removed first.  If @var{value} is
1592 @code{0}, then the new entry will the special null type of entry
1593 (mentioned above).
1594 @end deftypefun
1596 @comment envz.h
1597 @comment GNU
1598 @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})
1599 The @code{envz_merge} function adds each entry in @var{envz2} to @var{envz},
1600 as if with @code{envz_add}, updating @code{*@var{envz}} and
1601 @code{*@var{envz_len}}.  If @var{override} is true, then values in @var{envz2}
1602 will supersede those with the same name in @var{envz}, otherwise not.
1604 Null entries are treated just like other entries in this respect, so a null
1605 entry in @var{envz} can prevent an entry of the same name in @var{envz2} from
1606 being added to @var{envz}, if @var{override} is false.
1607 @end deftypefun
1609 @comment envz.h
1610 @comment GNU
1611 @deftypefun {void} envz_strip (char **@var{envz}, size_t *@var{envz_len})
1612 The @code{envz_strip} function removes any null entries from @var{envz},
1613 updating @code{*@var{envz}} and @code{*@var{envz_len}}.
1614 @end deftypefun