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 (null-terminated byte sequences) are an important part of
6 many programs. @Theglibc{} provides an extensive set of string
7 utility functions, including functions for copying, concatenating,
8 comparing, and searching strings. Many of these functions can also
9 operate on arbitrary regions of storage; for example, the @code{memcpy}
10 function can be used to copy the contents of any kind of array.
12 It's fairly common for beginning C programmers to ``reinvent the wheel''
13 by duplicating this functionality in their own code, but it pays to
14 become familiar with the library functions and to make use of them,
15 since this offers benefits in maintenance, efficiency, and portability.
17 For instance, you could easily compare one string to another in two
18 lines of C code, but if you use the built-in @code{strcmp} function,
19 you're less likely to make a mistake. And, since these library
20 functions are typically highly optimized, your program may run faster
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 Strings and Arrays:: Functions to copy strings and arrays.
29 * Concatenating Strings:: Functions to concatenate strings while copying.
30 * Truncating Strings:: Functions to truncate strings while copying.
31 * String/Array Comparison:: Functions for byte-wise and character-wise
33 * Collation Functions:: Functions for collating strings.
34 * Search Functions:: Searching for a specific element or substring.
35 * Finding Tokens in a String:: Splitting a string into tokens by looking
37 * strfry:: Function for flash-cooking a string.
38 * Trivial Encryption:: Obscuring data.
39 * Encode Binary Data:: Encoding and Decoding of Binary Data.
40 * Argz and Envz Vectors:: Null-separated string vectors.
43 @node Representation of Strings
44 @section Representation of Strings
45 @cindex string, representation of
47 This section is a quick summary of string concepts for beginning C
48 programmers. It describes how strings are represented in C
49 and some common pitfalls. If you are already familiar with this
50 material, you can skip this section.
53 A @dfn{string} is a null-terminated array of bytes of type @code{char},
54 including the terminating null byte. String-valued
55 variables are usually declared to be pointers of type @code{char *}.
56 Such variables do not include space for the text of a string; that has
57 to be stored somewhere else---in an array variable, a string constant,
58 or dynamically allocated memory (@pxref{Memory Allocation}). It's up to
59 you to store the address of the chosen memory space into the pointer
60 variable. Alternatively you can store a @dfn{null pointer} in the
61 pointer variable. The null pointer does not point anywhere, so
62 attempting to reference the string it points to gets an error.
64 @cindex multibyte character
65 @cindex multibyte string
67 A @dfn{multibyte character} is a sequence of one or more bytes that
68 represents a single character using the locale's encoding scheme; a
69 null byte always represents the null character. A @dfn{multibyte
70 string} is a string that consists entirely of multibyte
71 characters. In contrast, a @dfn{wide string} is a null-terminated
72 sequence of @code{wchar_t} objects. A wide-string variable is usually
73 declared to be a pointer of type @code{wchar_t *}, by analogy with
74 string variables and @code{char *}. @xref{Extended Char Intro}.
77 @cindex null wide character
78 By convention, the @dfn{null byte}, @code{'\0'},
79 marks the end of a string and the @dfn{null wide character},
80 @code{L'\0'}, marks the end of a wide string. For example, in
81 testing to see whether the @code{char *} variable @var{p} points to a
82 null byte marking the end of a string, you can write
83 @code{!*@var{p}} or @code{*@var{p} == '\0'}.
85 A null byte is quite different conceptually from a null pointer,
86 although both are represented by the integer constant @code{0}.
88 @cindex string literal
89 A @dfn{string literal} appears in C program source as a multibyte
90 string between double-quote characters (@samp{"}). If the
91 initial double-quote character is immediately preceded by a capital
92 @samp{L} (ell) character (as in @code{L"foo"}), it is a wide string
93 literal. String literals can also contribute to @dfn{string
94 concatenation}: @code{"a" "b"} is the same as @code{"ab"}.
95 For wide strings one can use either
96 @code{L"a" L"b"} or @code{L"a" "b"}. Modification of string literals is
97 not allowed by the GNU C compiler, because literals are placed in
100 Arrays that are declared @code{const} cannot be modified
101 either. It's generally good style to declare non-modifiable string
102 pointers to be of type @code{const char *}, since this often allows the
103 C compiler to detect accidental modifications as well as providing some
104 amount of documentation about what your program intends to do with the
107 The amount of memory allocated for a byte array may extend past the null byte
108 that marks the end of the string that the array contains. In this
109 document, the term @dfn{allocated size} is always used to refer to the
110 total amount of memory allocated for an array, while the term
111 @dfn{length} refers to the number of bytes up to (but not including)
112 the terminating null byte. Wide strings are similar, except their
113 sizes and lengths count wide characters, not bytes.
114 @cindex length of string
115 @cindex allocation size of string
116 @cindex size of string
117 @cindex string length
118 @cindex string allocation
120 A notorious source of program bugs is trying to put more bytes into a
121 string than fit in its allocated size. When writing code that extends
122 strings or moves bytes into a pre-allocated array, you should be
123 very careful to keep track of the length of the text and make explicit
124 checks for overflowing the array. Many of the library functions
125 @emph{do not} do this for you! Remember also that you need to allocate
126 an extra byte to hold the null byte that marks the end of the
129 @cindex single-byte string
130 @cindex multibyte string
131 Originally strings were sequences of bytes where each byte represented a
132 single character. This is still true today if the strings are encoded
133 using a single-byte character encoding. Things are different if the
134 strings are encoded using a multibyte encoding (for more information on
135 encodings see @ref{Extended Char Intro}). There is no difference in
136 the programming interface for these two kind of strings; the programmer
137 has to be aware of this and interpret the byte sequences accordingly.
139 But since there is no separate interface taking care of these
140 differences the byte-based string functions are sometimes hard to use.
141 Since the count parameters of these functions specify bytes a call to
142 @code{memcpy} could cut a multibyte character in the middle and put an
143 incomplete (and therefore unusable) byte sequence in the target buffer.
146 To avoid these problems later versions of the @w{ISO C} standard
147 introduce a second set of functions which are operating on @dfn{wide
148 characters} (@pxref{Extended Char Intro}). These functions don't have
149 the problems the single-byte versions have since every wide character is
150 a legal, interpretable value. This does not mean that cutting wide
151 strings at arbitrary points is without problems. It normally
152 is for alphabet-based languages (except for non-normalized text) but
153 languages based on syllables still have the problem that more than one
154 wide character is necessary to complete a logical unit. This is a
155 higher level problem which the @w{C library} functions are not designed
156 to solve. But it is at least good that no invalid byte sequences can be
157 created. Also, the higher level functions can also much more easily operate
158 on wide characters than on multibyte characters so that a common strategy
159 is to use wide characters internally whenever text is more than simply
162 The remaining of this chapter will discuss the functions for handling
163 wide strings in parallel with the discussion of
164 strings since there is almost always an exact equivalent
167 @node String/Array Conventions
168 @section String and Array Conventions
170 This chapter describes both functions that work on arbitrary arrays or
171 blocks of memory, and functions that are specific to strings and wide
174 Functions that operate on arbitrary blocks of memory have names
175 beginning with @samp{mem} and @samp{wmem} (such as @code{memcpy} and
176 @code{wmemcpy}) and invariably take an argument which specifies the size
177 (in bytes and wide characters respectively) of the block of memory to
178 operate on. The array arguments and return values for these functions
179 have type @code{void *} or @code{wchar_t}. As a matter of style, the
180 elements of the arrays used with the @samp{mem} functions are referred
181 to as ``bytes''. You can pass any kind of pointer to these functions,
182 and the @code{sizeof} operator is useful in computing the value for the
183 size argument. Parameters to the @samp{wmem} functions must be of type
184 @code{wchar_t *}. These functions are not really usable with anything
185 but arrays of this type.
187 In contrast, functions that operate specifically on strings and wide
188 strings have names beginning with @samp{str} and @samp{wcs}
189 respectively (such as @code{strcpy} and @code{wcscpy}) and look for a
190 terminating null byte or null wide character instead of requiring an explicit
191 size argument to be passed. (Some of these functions accept a specified
192 maximum length, but they also check for premature termination.)
193 The array arguments and return values for these
194 functions have type @code{char *} and @code{wchar_t *} respectively, and
195 the array elements are referred to as ``bytes'' and ``wide
198 In many cases, there are both @samp{mem} and @samp{str}/@samp{wcs}
199 versions of a function. The one that is more appropriate to use depends
200 on the exact situation. When your program is manipulating arbitrary
201 arrays or blocks of storage, then you should always use the @samp{mem}
202 functions. On the other hand, when you are manipulating
203 strings it is usually more convenient to use the @samp{str}/@samp{wcs}
204 functions, unless you already know the length of the string in advance.
205 The @samp{wmem} functions should be used for wide character arrays with
209 @cindex parameter promotion
210 Some of the memory and string functions take single characters as
211 arguments. Since a value of type @code{char} is automatically promoted
212 into a value of type @code{int} when used as a parameter, the functions
213 are declared with @code{int} as the type of the parameter in question.
214 In case of the wide character functions the situation is similar: the
215 parameter type for a single wide character is @code{wint_t} and not
216 @code{wchar_t}. This would for many implementations not be necessary
217 since @code{wchar_t} is large enough to not be automatically
218 promoted, but since the @w{ISO C} standard does not require such a
219 choice of types the @code{wint_t} type is used.
222 @section String Length
224 You can get the length of a string using the @code{strlen} function.
225 This function is declared in the header file @file{string.h}.
230 @deftypefun size_t strlen (const char *@var{s})
231 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
232 The @code{strlen} function returns the length of the
233 string @var{s} in bytes. (In other words, it returns the offset of the
234 terminating null byte within the array.)
238 strlen ("hello, world")
242 When applied to an array, the @code{strlen} function returns
243 the length of the string stored there, not its allocated size. You can
244 get the allocated size of the array that holds a string using
245 the @code{sizeof} operator:
248 char string[32] = "hello, world";
255 But beware, this will not work unless @var{string} is the
256 array itself, not a pointer to it. For example:
259 char string[32] = "hello, world";
264 @result{} 4 /* @r{(on a machine with 4 byte pointers)} */
267 This is an easy mistake to make when you are working with functions that
268 take string arguments; those arguments are always pointers, not arrays.
270 It must also be noted that for multibyte encoded strings the return
271 value does not have to correspond to the number of characters in the
272 string. To get this value the string can be converted to wide
273 characters and @code{wcslen} can be used or something like the following
277 /* @r{The input is in @code{string}.}
278 @r{The length is expected in @code{n}.} */
281 char *scopy = string;
282 /* In initial state. */
283 memset (&t, '\0', sizeof (t));
284 /* Determine number of characters. */
285 n = mbsrtowcs (NULL, &scopy, strlen (scopy), &t);
289 This is cumbersome to do so if the number of characters (as opposed to
290 bytes) is needed often it is better to work with wide characters.
293 The wide character equivalent is declared in @file{wchar.h}.
297 @deftypefun size_t wcslen (const wchar_t *@var{ws})
298 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
299 The @code{wcslen} function is the wide character equivalent to
300 @code{strlen}. The return value is the number of wide characters in the
301 wide string pointed to by @var{ws} (this is also the offset of
302 the terminating null wide character of @var{ws}).
304 Since there are no multi wide character sequences making up one wide
305 character the return value is not only the offset in the array, it is
306 also the number of wide characters.
308 This function was introduced in @w{Amendment 1} to @w{ISO C90}.
313 @deftypefun size_t strnlen (const char *@var{s}, size_t @var{maxlen})
314 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
315 If the array @var{s} of size @var{maxlen} contains a null byte,
316 the @code{strnlen} function returns the length of the string @var{s} in
318 returns @var{maxlen}. Therefore this function is equivalent to
319 @code{(strlen (@var{s}) < @var{maxlen} ? strlen (@var{s}) : @var{maxlen})}
321 is more efficient and works even if @var{s} is not null-terminated so
322 long as @var{maxlen} does not exceed the size of @var{s}'s array.
325 char string[32] = "hello, world";
332 This function is a GNU extension and is declared in @file{string.h}.
337 @deftypefun size_t wcsnlen (const wchar_t *@var{ws}, size_t @var{maxlen})
338 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
339 @code{wcsnlen} is the wide character equivalent to @code{strnlen}. The
340 @var{maxlen} parameter specifies the maximum number of wide characters.
342 This function is a GNU extension and is declared in @file{wchar.h}.
345 @node Copying Strings and Arrays
346 @section Copying Strings and Arrays
348 You can use the functions described in this section to copy the contents
349 of strings, wide strings, and arrays. The @samp{str} and @samp{mem}
350 functions are declared in @file{string.h} while the @samp{w} functions
351 are declared in @file{wchar.h}.
354 @cindex copying strings and arrays
355 @cindex string copy functions
356 @cindex array copy functions
357 @cindex concatenating strings
358 @cindex string concatenation functions
360 A helpful way to remember the ordering of the arguments to the functions
361 in this section is that it corresponds to an assignment expression, with
362 the destination array specified to the left of the source array. Most
363 of these functions return the address of the destination array; a few
364 return the address of the destination's terminating null, or of just
365 past the destination.
367 Most of these functions do not work properly if the source and
368 destination arrays overlap. For example, if the beginning of the
369 destination array overlaps the end of the source array, the original
370 contents of that part of the source array may get overwritten before it
371 is copied. Even worse, in the case of the string functions, the null
372 byte marking the end of the string may be lost, and the copy
373 function might get stuck in a loop trashing all the memory allocated to
376 All functions that have problems copying between overlapping arrays are
377 explicitly identified in this manual. In addition to functions in this
378 section, there are a few others like @code{sprintf} (@pxref{Formatted
379 Output Functions}) and @code{scanf} (@pxref{Formatted Input
384 @deftypefun {void *} memcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
385 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
386 The @code{memcpy} function copies @var{size} bytes from the object
387 beginning at @var{from} into the object beginning at @var{to}. The
388 behavior of this function is undefined if the two arrays @var{to} and
389 @var{from} overlap; use @code{memmove} instead if overlapping is possible.
391 The value returned by @code{memcpy} is the value of @var{to}.
393 Here is an example of how you might use @code{memcpy} to copy the
394 contents of an array:
397 struct foo *oldarray, *newarray;
400 memcpy (new, old, arraysize * sizeof (struct foo));
406 @deftypefun {wchar_t *} wmemcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
407 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
408 The @code{wmemcpy} function copies @var{size} wide characters from the object
409 beginning at @var{wfrom} into the object beginning at @var{wto}. The
410 behavior of this function is undefined if the two arrays @var{wto} and
411 @var{wfrom} overlap; use @code{wmemmove} instead if overlapping is possible.
413 The following is a possible implementation of @code{wmemcpy} but there
414 are more optimizations possible.
418 wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
421 return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));
425 The value returned by @code{wmemcpy} is the value of @var{wto}.
427 This function was introduced in @w{Amendment 1} to @w{ISO C90}.
432 @deftypefun {void *} mempcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
433 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
434 The @code{mempcpy} function is nearly identical to the @code{memcpy}
435 function. It copies @var{size} bytes from the object beginning at
436 @code{from} into the object pointed to by @var{to}. But instead of
437 returning the value of @var{to} it returns a pointer to the byte
438 following the last written byte in the object beginning at @var{to}.
439 I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
441 This function is useful in situations where a number of objects shall be
442 copied to consecutive memory positions.
446 combine (void *o1, size_t s1, void *o2, size_t s2)
448 void *result = malloc (s1 + s2);
450 mempcpy (mempcpy (result, o1, s1), o2, s2);
455 This function is a GNU extension.
460 @deftypefun {wchar_t *} wmempcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
461 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
462 The @code{wmempcpy} function is nearly identical to the @code{wmemcpy}
463 function. It copies @var{size} wide characters from the object
464 beginning at @code{wfrom} into the object pointed to by @var{wto}. But
465 instead of returning the value of @var{wto} it returns a pointer to the
466 wide character following the last written wide character in the object
467 beginning at @var{wto}. I.e., the value is @code{@var{wto} + @var{size}}.
469 This function is useful in situations where a number of objects shall be
470 copied to consecutive memory positions.
472 The following is a possible implementation of @code{wmemcpy} but there
473 are more optimizations possible.
477 wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
480 return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
484 This function is a GNU extension.
489 @deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
490 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
491 @code{memmove} copies the @var{size} bytes at @var{from} into the
492 @var{size} bytes at @var{to}, even if those two blocks of space
493 overlap. In the case of overlap, @code{memmove} is careful to copy the
494 original values of the bytes in the block at @var{from}, including those
495 bytes which also belong to the block at @var{to}.
497 The value returned by @code{memmove} is the value of @var{to}.
502 @deftypefun {wchar_t *} wmemmove (wchar_t *@var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
503 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
504 @code{wmemmove} copies the @var{size} wide characters at @var{wfrom}
505 into the @var{size} wide characters at @var{wto}, even if those two
506 blocks of space overlap. In the case of overlap, @code{wmemmove} is
507 careful to copy the original values of the wide characters in the block
508 at @var{wfrom}, including those wide characters which also belong to the
511 The following is a possible implementation of @code{wmemcpy} but there
512 are more optimizations possible.
516 wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
519 return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
523 The value returned by @code{wmemmove} is the value of @var{wto}.
525 This function is a GNU extension.
530 @deftypefun {void *} memccpy (void *restrict @var{to}, const void *restrict @var{from}, int @var{c}, size_t @var{size})
531 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
532 This function copies no more than @var{size} bytes from @var{from} to
533 @var{to}, stopping if a byte matching @var{c} is found. The return
534 value is a pointer into @var{to} one byte past where @var{c} was copied,
535 or a null pointer if no byte matching @var{c} appeared in the first
536 @var{size} bytes of @var{from}.
541 @deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
542 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
543 This function copies the value of @var{c} (converted to an
544 @code{unsigned char}) into each of the first @var{size} bytes of the
545 object beginning at @var{block}. It returns the value of @var{block}.
550 @deftypefun {wchar_t *} wmemset (wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
551 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
552 This function copies the value of @var{wc} into each of the first
553 @var{size} wide characters of the object beginning at @var{block}. It
554 returns the value of @var{block}.
559 @deftypefun {char *} strcpy (char *restrict @var{to}, const char *restrict @var{from})
560 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
561 This copies bytes from the string @var{from} (up to and including
562 the terminating null byte) into the string @var{to}. Like
563 @code{memcpy}, this function has undefined results if the strings
564 overlap. The return value is the value of @var{to}.
569 @deftypefun {wchar_t *} wcscpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
570 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
571 This copies wide characters from the wide string @var{wfrom} (up to and
572 including the terminating null wide character) into the string
573 @var{wto}. Like @code{wmemcpy}, this function has undefined results if
574 the strings overlap. The return value is the value of @var{wto}.
578 @deftypefun {char *} strdup (const char *@var{s})
579 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
580 This function copies the string @var{s} into a newly
581 allocated string. The string is allocated using @code{malloc}; see
582 @ref{Unconstrained Allocation}. If @code{malloc} cannot allocate space
583 for the new string, @code{strdup} returns a null pointer. Otherwise it
584 returns a pointer to the new string.
589 @deftypefun {wchar_t *} wcsdup (const wchar_t *@var{ws})
590 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
591 This function copies the wide string @var{ws}
592 into a newly allocated string. The string is allocated using
593 @code{malloc}; see @ref{Unconstrained Allocation}. If @code{malloc}
594 cannot allocate space for the new string, @code{wcsdup} returns a null
595 pointer. Otherwise it returns a pointer to the new wide string.
597 This function is a GNU extension.
601 @comment Unknown origin
602 @deftypefun {char *} stpcpy (char *restrict @var{to}, const char *restrict @var{from})
603 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
604 This function is like @code{strcpy}, except that it returns a pointer to
605 the end of the string @var{to} (that is, the address of the terminating
606 null byte @code{to + strlen (from)}) rather than the beginning.
608 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
609 and @samp{bar} to produce @samp{foobar}, which it then prints.
612 @include stpcpy.c.texi
615 This function is part of POSIX.1-2008 and later editions, but was
616 available in @theglibc{} and other systems as an extension long before
619 Its behavior is undefined if the strings overlap. The function is
620 declared in @file{string.h}.
625 @deftypefun {wchar_t *} wcpcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
626 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
627 This function is like @code{wcscpy}, except that it returns a pointer to
628 the end of the string @var{wto} (that is, the address of the terminating
629 null wide character @code{wto + wcslen (wfrom)}) rather than the beginning.
631 This function is not part of ISO or POSIX but was found useful while
632 developing @theglibc{} itself.
634 The behavior of @code{wcpcpy} is undefined if the strings overlap.
636 @code{wcpcpy} is a GNU extension and is declared in @file{wchar.h}.
641 @deftypefn {Macro} {char *} strdupa (const char *@var{s})
642 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
643 This macro is similar to @code{strdup} but allocates the new string
644 using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
645 Automatic}). This means of course the returned string has the same
646 limitations as any block of memory allocated using @code{alloca}.
648 For obvious reasons @code{strdupa} is implemented only as a macro;
649 you cannot get the address of this function. Despite this limitation
650 it is a useful function. The following code shows a situation where
651 using @code{malloc} would be a lot more expensive.
654 @include strdupa.c.texi
657 Please note that calling @code{strtok} using @var{path} directly is
658 invalid. It is also not allowed to call @code{strdupa} in the argument
659 list of @code{strtok} since @code{strdupa} uses @code{alloca}
660 (@pxref{Variable Size Automatic}) can interfere with the parameter
663 This function is only available if GNU CC is used.
668 @deftypefun void bcopy (const void *@var{from}, void *@var{to}, size_t @var{size})
669 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
670 This is a partially obsolete alternative for @code{memmove}, derived from
671 BSD. Note that it is not quite equivalent to @code{memmove}, because the
672 arguments are not in the same order and there is no return value.
677 @deftypefun void bzero (void *@var{block}, size_t @var{size})
678 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
679 This is a partially obsolete alternative for @code{memset}, derived from
680 BSD. Note that it is not as general as @code{memset}, because the only
681 value it can store is zero.
684 @node Concatenating Strings
685 @section Concatenating Strings
688 @cindex concatenating strings
689 @cindex string concatenation functions
691 The functions described in this section concatenate the contents of a
692 string or wide string to another. They follow the string-copying
693 functions in their conventions. @xref{Copying Strings and Arrays}.
694 @samp{strcat} is declared in the header file @file{string.h} while
695 @samp{wcscat} is declared in @file{wchar.h}.
699 @deftypefun {char *} strcat (char *restrict @var{to}, const char *restrict @var{from})
700 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
701 The @code{strcat} function is similar to @code{strcpy}, except that the
702 bytes from @var{from} are concatenated or appended to the end of
703 @var{to}, instead of overwriting it. That is, the first byte from
704 @var{from} overwrites the null byte marking the end of @var{to}.
706 An equivalent definition for @code{strcat} would be:
710 strcat (char *restrict to, const char *restrict from)
712 strcpy (to + strlen (to), from);
717 This function has undefined results if the strings overlap.
719 As noted below, this function has significant performance issues.
724 @deftypefun {wchar_t *} wcscat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
725 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
726 The @code{wcscat} function is similar to @code{wcscpy}, except that the
727 wide characters from @var{wfrom} are concatenated or appended to the end of
728 @var{wto}, instead of overwriting it. That is, the first wide character from
729 @var{wfrom} overwrites the null wide character marking the end of @var{wto}.
731 An equivalent definition for @code{wcscat} would be:
735 wcscat (wchar_t *wto, const wchar_t *wfrom)
737 wcscpy (wto + wcslen (wto), wfrom);
742 This function has undefined results if the strings overlap.
744 As noted below, this function has significant performance issues.
747 Programmers using the @code{strcat} or @code{wcscat} function (or the
748 @code{strncat} or @code{wcsncat} functions defined in
749 a later section, for that matter)
750 can easily be recognized as lazy and reckless. In almost all situations
751 the lengths of the participating strings are known (it better should be
752 since how can one otherwise ensure the allocated size of the buffer is
753 sufficient?) Or at least, one could know them if one keeps track of the
754 results of the various function calls. But then it is very inefficient
755 to use @code{strcat}/@code{wcscat}. A lot of time is wasted finding the
756 end of the destination string so that the actual copying can start.
757 This is a common example:
761 /* @r{This function concatenates arbitrarily many strings. The last}
762 @r{parameter must be @code{NULL}.} */
764 concat (const char *str, @dots{})
774 /* @r{Determine how much space we need.} */
775 for (s = str; s != NULL; s = va_arg (ap, const char *))
780 result = (char *) malloc (total);
785 /* @r{Copy the strings.} */
786 for (s = str; s != NULL; s = va_arg (ap2, const char *))
796 This looks quite simple, especially the second loop where the strings
797 are actually copied. But these innocent lines hide a major performance
798 penalty. Just imagine that ten strings of 100 bytes each have to be
799 concatenated. For the second string we search the already stored 100
800 bytes for the end of the string so that we can append the next string.
801 For all strings in total the comparisons necessary to find the end of
802 the intermediate results sums up to 5500! If we combine the copying
803 with the search for the allocation we can write this function more
808 concat (const char *str, @dots{})
811 size_t allocated = 100;
812 char *result = (char *) malloc (allocated);
823 for (s = str; s != NULL; s = va_arg (ap, const char *))
825 size_t len = strlen (s);
827 /* @r{Resize the allocated memory if necessary.} */
828 if (wp + len + 1 > result + allocated)
830 allocated = (allocated + len) * 2;
831 newp = (char *) realloc (result, allocated);
837 wp = newp + (wp - result);
841 wp = mempcpy (wp, s, len);
844 /* @r{Terminate the result string.} */
847 /* @r{Resize memory to the optimal size.} */
848 newp = realloc (result, wp - result);
859 With a bit more knowledge about the input strings one could fine-tune
860 the memory allocation. The difference we are pointing to here is that
861 we don't use @code{strcat} anymore. We always keep track of the length
862 of the current intermediate result so we can save ourselves the search for the
863 end of the string and use @code{mempcpy}. Please note that we also
864 don't use @code{stpcpy} which might seem more natural since we are handling
865 strings. But this is not necessary since we already know the
866 length of the string and therefore can use the faster memory copying
867 function. The example would work for wide characters the same way.
869 Whenever a programmer feels the need to use @code{strcat} she or he
870 should think twice and look through the program to see whether the code cannot
871 be rewritten to take advantage of already calculated results. Again: it
872 is almost always unnecessary to use @code{strcat}.
874 @node Truncating Strings
875 @section Truncating Strings while Copying
876 @cindex truncating strings
877 @cindex string truncation
879 The functions described in this section copy or concatenate the
880 possibly-truncated contents of a string or array to another, and
881 similarly for wide strings. They follow the string-copying functions
882 in their header conventions. @xref{Copying Strings and Arrays}. The
883 @samp{str} functions are declared in the header file @file{string.h}
884 and the @samp{wc} functions are declared in the file @file{wchar.h}.
887 @deftypefun {char *} strncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
888 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
889 This function is similar to @code{strcpy} but always copies exactly
890 @var{size} bytes into @var{to}.
892 If @var{from} does not contain a null byte in its first @var{size}
893 bytes, @code{strncpy} copies just the first @var{size} bytes. In this
894 case no null terminator is written into @var{to}.
896 Otherwise @var{from} must be a string with length less than
897 @var{size}. In this case @code{strncpy} copies all of @var{from},
898 followed by enough null bytes to add up to @var{size} bytes in all.
900 The behavior of @code{strncpy} is undefined if the strings overlap.
902 This function was designed for now-rarely-used arrays consisting of
903 non-null bytes followed by zero or more null bytes. It needs to set
904 all @var{size} bytes of the destination, even when @var{size} is much
905 greater than the length of @var{from}. As noted below, this function
906 is generally a poor choice for processing text.
911 @deftypefun {wchar_t *} wcsncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
912 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
913 This function is similar to @code{wcscpy} but always copies exactly
914 @var{size} wide characters into @var{wto}.
916 If @var{wfrom} does not contain a null wide character in its first
917 @var{size} wide characters, then @code{wcsncpy} copies just the first
918 @var{size} wide characters. In this case no null terminator is
919 written into @var{wto}.
921 Otherwise @var{wfrom} must be a wide string with length less than
922 @var{size}. In this case @code{wcsncpy} copies all of @var{wfrom},
923 followed by enough null wide characters to add up to @var{size} wide
926 The behavior of @code{wcsncpy} is undefined if the strings overlap.
928 This function is the wide-character counterpart of @code{strncpy} and
929 suffers from most of the problems that @code{strncpy} does. For
930 example, as noted below, this function is generally a poor choice for
936 @deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
937 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
938 This function is similar to @code{strdup} but always copies at most
939 @var{size} bytes into the newly allocated string.
941 If the length of @var{s} is more than @var{size}, then @code{strndup}
942 copies just the first @var{size} bytes and adds a closing null byte.
943 Otherwise all bytes are copied and the string is terminated.
945 This function differs from @code{strncpy} in that it always terminates
946 the destination string.
948 As noted below, this function is generally a poor choice for
951 @code{strndup} is a GNU extension.
956 @deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
957 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
958 This function is similar to @code{strndup} but like @code{strdupa} it
959 allocates the new string using @code{alloca} @pxref{Variable Size
960 Automatic}. The same advantages and limitations of @code{strdupa} are
961 valid for @code{strndupa}, too.
963 This function is implemented only as a macro, just like @code{strdupa}.
964 Just as @code{strdupa} this macro also must not be used inside the
965 parameter list in a function call.
967 As noted below, this function is generally a poor choice for
970 @code{strndupa} is only available if GNU CC is used.
975 @deftypefun {char *} stpncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
976 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
977 This function is similar to @code{stpcpy} but copies always exactly
978 @var{size} bytes into @var{to}.
980 If the length of @var{from} is more than @var{size}, then @code{stpncpy}
981 copies just the first @var{size} bytes and returns a pointer to the
982 byte directly following the one which was copied last. Note that in
983 this case there is no null terminator written into @var{to}.
985 If the length of @var{from} is less than @var{size}, then @code{stpncpy}
986 copies all of @var{from}, followed by enough null bytes to add up
987 to @var{size} bytes in all. This behavior is rarely useful, but it
988 is implemented to be useful in contexts where this behavior of the
989 @code{strncpy} is used. @code{stpncpy} returns a pointer to the
990 @emph{first} written null byte.
992 This function is not part of ISO or POSIX but was found useful while
993 developing @theglibc{} itself.
995 Its behavior is undefined if the strings overlap. The function is
996 declared in @file{string.h}.
998 As noted below, this function is generally a poor choice for
1004 @deftypefun {wchar_t *} wcpncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
1005 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1006 This function is similar to @code{wcpcpy} but copies always exactly
1007 @var{wsize} wide characters into @var{wto}.
1009 If the length of @var{wfrom} is more than @var{size}, then
1010 @code{wcpncpy} copies just the first @var{size} wide characters and
1011 returns a pointer to the wide character directly following the last
1012 non-null wide character which was copied last. Note that in this case
1013 there is no null terminator written into @var{wto}.
1015 If the length of @var{wfrom} is less than @var{size}, then @code{wcpncpy}
1016 copies all of @var{wfrom}, followed by enough null wide characters to add up
1017 to @var{size} wide characters in all. This behavior is rarely useful, but it
1018 is implemented to be useful in contexts where this behavior of the
1019 @code{wcsncpy} is used. @code{wcpncpy} returns a pointer to the
1020 @emph{first} written null wide character.
1022 This function is not part of ISO or POSIX but was found useful while
1023 developing @theglibc{} itself.
1025 Its behavior is undefined if the strings overlap.
1027 As noted below, this function is generally a poor choice for
1030 @code{wcpncpy} is a GNU extension.
1035 @deftypefun {char *} strncat (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
1036 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1037 This function is like @code{strcat} except that not more than @var{size}
1038 bytes from @var{from} are appended to the end of @var{to}, and
1039 @var{from} need not be null-terminated. A single null byte is also
1040 always appended to @var{to}, so the total
1041 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
1042 longer than its initial length.
1044 The @code{strncat} function could be implemented like this:
1049 strncat (char *to, const char *from, size_t size)
1051 size_t len = strlen (to);
1052 memcpy (to + len, from, strnlen (from, size));
1053 to[len + strnlen (from, size)] = '\0';
1059 The behavior of @code{strncat} is undefined if the strings overlap.
1061 As a companion to @code{strncpy}, @code{strncat} was designed for
1062 now-rarely-used arrays consisting of non-null bytes followed by zero
1063 or more null bytes. As noted below, this function is generally a poor
1064 choice for processing text. Also, this function has significant
1065 performance issues. @xref{Concatenating Strings}.
1070 @deftypefun {wchar_t *} wcsncat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
1071 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1072 This function is like @code{wcscat} except that not more than @var{size}
1073 wide characters from @var{from} are appended to the end of @var{to},
1074 and @var{from} need not be null-terminated. A single null wide
1075 character is also always appended to @var{to}, so the total allocated
1076 size of @var{to} must be at least @code{wcsnlen (@var{wfrom},
1077 @var{size}) + 1} wide characters longer than its initial length.
1079 The @code{wcsncat} function could be implemented like this:
1084 wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom,
1087 size_t len = wcslen (wto);
1088 memcpy (wto + len, wfrom, wcsnlen (wfrom, size) * sizeof (wchar_t));
1089 wto[len + wcsnlen (wfrom, size)] = L'\0';
1095 The behavior of @code{wcsncat} is undefined if the strings overlap.
1097 As noted below, this function is generally a poor choice for
1098 processing text. Also, this function has significant performance
1099 issues. @xref{Concatenating Strings}.
1102 Because these functions can abruptly truncate strings or wide strings,
1103 they are generally poor choices for processing text. When coping or
1104 concatening multibyte strings, they can truncate within a multibyte
1105 character so that the result is not a valid multibyte string. When
1106 combining or concatenating multibyte or wide strings, they may
1107 truncate the output after a combining character, resulting in a
1108 corrupted grapheme. They can cause bugs even when processing
1109 single-byte strings: for example, when calculating an ASCII-only user
1110 name, a truncated name can identify the wrong user.
1112 Although some buffer overruns can be prevented by manually replacing
1113 calls to copying functions with calls to truncation functions, there
1114 are often easier and safer automatic techniques that cause buffer
1115 overruns to reliably terminate a program, such as GCC's
1116 @option{-fcheck-pointer-bounds} and @option{-fsanitize=address}
1117 options. @xref{Debugging Options,, Options for Debugging Your Program
1118 or GCC, gcc.info, Using GCC}. Because truncation functions can mask
1119 application bugs that would otherwise be caught by the automatic
1120 techniques, these functions should be used only when the application's
1121 underlying logic requires truncation.
1123 @strong{Note:} GNU programs should not truncate strings or wide
1124 strings to fit arbitrary size limits. @xref{Semantics, , Writing
1125 Robust Programs, standards, The GNU Coding Standards}. Instead of
1126 string-truncation functions, it is usually better to use dynamic
1127 memory allocation (@pxref{Unconstrained Allocation}) and functions
1128 such as @code{strdup} or @code{asprintf} to construct strings.
1130 @node String/Array Comparison
1131 @section String/Array Comparison
1132 @cindex comparing strings and arrays
1133 @cindex string comparison functions
1134 @cindex array comparison functions
1135 @cindex predicates on strings
1136 @cindex predicates on arrays
1138 You can use the functions in this section to perform comparisons on the
1139 contents of strings and arrays. As well as checking for equality, these
1140 functions can also be used as the ordering functions for sorting
1141 operations. @xref{Searching and Sorting}, for an example of this.
1143 Unlike most comparison operations in C, the string comparison functions
1144 return a nonzero value if the strings are @emph{not} equivalent rather
1145 than if they are. The sign of the value indicates the relative ordering
1146 of the first part of the strings that are not equivalent: a
1147 negative value indicates that the first string is ``less'' than the
1148 second, while a positive value indicates that the first string is
1151 The most common use of these functions is to check only for equality.
1152 This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
1154 All of these functions are declared in the header file @file{string.h}.
1159 @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
1160 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1161 The function @code{memcmp} compares the @var{size} bytes of memory
1162 beginning at @var{a1} against the @var{size} bytes of memory beginning
1163 at @var{a2}. The value returned has the same sign as the difference
1164 between the first differing pair of bytes (interpreted as @code{unsigned
1165 char} objects, then promoted to @code{int}).
1167 If the contents of the two blocks are equal, @code{memcmp} returns
1173 @deftypefun int wmemcmp (const wchar_t *@var{a1}, const wchar_t *@var{a2}, size_t @var{size})
1174 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1175 The function @code{wmemcmp} compares the @var{size} wide characters
1176 beginning at @var{a1} against the @var{size} wide characters beginning
1177 at @var{a2}. The value returned is smaller than or larger than zero
1178 depending on whether the first differing wide character is @var{a1} is
1179 smaller or larger than the corresponding wide character in @var{a2}.
1181 If the contents of the two blocks are equal, @code{wmemcmp} returns
1185 On arbitrary arrays, the @code{memcmp} function is mostly useful for
1186 testing equality. It usually isn't meaningful to do byte-wise ordering
1187 comparisons on arrays of things other than bytes. For example, a
1188 byte-wise comparison on the bytes that make up floating-point numbers
1189 isn't likely to tell you anything about the relationship between the
1190 values of the floating-point numbers.
1192 @code{wmemcmp} is really only useful to compare arrays of type
1193 @code{wchar_t} since the function looks at @code{sizeof (wchar_t)} bytes
1194 at a time and this number of bytes is system dependent.
1196 You should also be careful about using @code{memcmp} to compare objects
1197 that can contain ``holes'', such as the padding inserted into structure
1198 objects to enforce alignment requirements, extra space at the end of
1199 unions, and extra bytes at the ends of strings whose length is less
1200 than their allocated size. The contents of these ``holes'' are
1201 indeterminate and may cause strange behavior when performing byte-wise
1202 comparisons. For more predictable results, perform an explicit
1203 component-wise comparison.
1205 For example, given a structure type definition like:
1221 you are better off writing a specialized comparison function to compare
1222 @code{struct foo} objects instead of comparing them with @code{memcmp}.
1226 @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
1227 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1228 The @code{strcmp} function compares the string @var{s1} against
1229 @var{s2}, returning a value that has the same sign as the difference
1230 between the first differing pair of bytes (interpreted as
1231 @code{unsigned char} objects, then promoted to @code{int}).
1233 If the two strings are equal, @code{strcmp} returns @code{0}.
1235 A consequence of the ordering used by @code{strcmp} is that if @var{s1}
1236 is an initial substring of @var{s2}, then @var{s1} is considered to be
1237 ``less than'' @var{s2}.
1239 @code{strcmp} does not take sorting conventions of the language the
1240 strings are written in into account. To get that one has to use
1246 @deftypefun int wcscmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1247 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1249 The @code{wcscmp} function compares the wide string @var{ws1}
1250 against @var{ws2}. The value returned is smaller than or larger than zero
1251 depending on whether the first differing wide character is @var{ws1} is
1252 smaller or larger than the corresponding wide character in @var{ws2}.
1254 If the two strings are equal, @code{wcscmp} returns @code{0}.
1256 A consequence of the ordering used by @code{wcscmp} is that if @var{ws1}
1257 is an initial substring of @var{ws2}, then @var{ws1} is considered to be
1258 ``less than'' @var{ws2}.
1260 @code{wcscmp} does not take sorting conventions of the language the
1261 strings are written in into account. To get that one has to use
1267 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
1268 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1269 @c Although this calls tolower multiple times, it's a macro, and
1270 @c strcasecmp is optimized so that the locale pointer is read only once.
1271 @c There are some asm implementations too, for which the single-read
1272 @c from locale TLS pointers also applies.
1273 This function is like @code{strcmp}, except that differences in case are
1274 ignored, and its arguments must be multibyte strings.
1275 How uppercase and lowercase characters are related is
1276 determined by the currently selected locale. In the standard @code{"C"}
1277 locale the characters @"A and @"a do not match but in a locale which
1278 regards these characters as parts of the alphabet they do match.
1281 @code{strcasecmp} is derived from BSD.
1286 @deftypefun int wcscasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1287 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1288 @c Since towlower is not a macro, the locale object may be read multiple
1290 This function is like @code{wcscmp}, except that differences in case are
1291 ignored. How uppercase and lowercase characters are related is
1292 determined by the currently selected locale. In the standard @code{"C"}
1293 locale the characters @"A and @"a do not match but in a locale which
1294 regards these characters as parts of the alphabet they do match.
1297 @code{wcscasecmp} is a GNU extension.
1302 @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
1303 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1304 This function is the similar to @code{strcmp}, except that no more than
1305 @var{size} bytes are compared. In other words, if the two
1306 strings are the same in their first @var{size} bytes, the
1307 return value is zero.
1312 @deftypefun int wcsncmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2}, size_t @var{size})
1313 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1314 This function is similar to @code{wcscmp}, except that no more than
1315 @var{size} wide characters are compared. In other words, if the two
1316 strings are the same in their first @var{size} wide characters, the
1317 return value is zero.
1322 @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
1323 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1324 This function is like @code{strncmp}, except that differences in case
1325 are ignored, and the compared parts of the arguments should consist of
1326 valid multibyte characters.
1327 Like @code{strcasecmp}, it is locale dependent how
1328 uppercase and lowercase characters are related.
1331 @code{strncasecmp} is a GNU extension.
1336 @deftypefun int wcsncasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{s2}, size_t @var{n})
1337 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1338 This function is like @code{wcsncmp}, except that differences in case
1339 are ignored. Like @code{wcscasecmp}, it is locale dependent how
1340 uppercase and lowercase characters are related.
1343 @code{wcsncasecmp} is a GNU extension.
1346 Here are some examples showing the use of @code{strcmp} and
1347 @code{strncmp} (equivalent examples can be constructed for the wide
1348 character functions). These examples assume the use of the ASCII
1349 character set. (If some other character set---say, EBCDIC---is used
1350 instead, then the glyphs are associated with different numeric codes,
1351 and the return values and ordering may differ.)
1354 strcmp ("hello", "hello")
1355 @result{} 0 /* @r{These two strings are the same.} */
1356 strcmp ("hello", "Hello")
1357 @result{} 32 /* @r{Comparisons are case-sensitive.} */
1358 strcmp ("hello", "world")
1359 @result{} -15 /* @r{The byte @code{'h'} comes before @code{'w'}.} */
1360 strcmp ("hello", "hello, world")
1361 @result{} -44 /* @r{Comparing a null byte against a comma.} */
1362 strncmp ("hello", "hello, world", 5)
1363 @result{} 0 /* @r{The initial 5 bytes are the same.} */
1364 strncmp ("hello, world", "hello, stupid world!!!", 5)
1365 @result{} 0 /* @r{The initial 5 bytes are the same.} */
1370 @deftypefun int strverscmp (const char *@var{s1}, const char *@var{s2})
1371 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1372 @c Calls isdigit multiple times, locale may change in between.
1373 The @code{strverscmp} function compares the string @var{s1} against
1374 @var{s2}, considering them as holding indices/version numbers. The
1375 return value follows the same conventions as found in the
1376 @code{strcmp} function. In fact, if @var{s1} and @var{s2} contain no
1377 digits, @code{strverscmp} behaves like @code{strcmp}
1378 (in the sense that the sign of the result is the same).
1380 The comparison algorithm which the @code{strverscmp} function implements
1381 differs slightly from other version-comparison algorithms. The
1382 implementation is based on a finite-state machine, whose behavior is
1387 The input strings are each split into sequences of non-digits and
1388 digits. These sequences can be empty at the beginning and end of the
1389 string. Digits are determined by the @code{isdigit} function and are
1390 thus subject to the current locale.
1393 Comparison starts with a (possibly empty) non-digit sequence. The first
1394 non-equal sequences of non-digits or digits determines the outcome of
1398 Corresponding non-digit sequences in both strings are compared
1399 lexicographically if their lengths are equal. If the lengths differ,
1400 the shorter non-digit sequence is extended with the input string
1401 character immediately following it (which may be the null terminator),
1402 the other sequence is truncated to be of the same (extended) length, and
1403 these two sequences are compared lexicographically. In the last case,
1404 the sequence comparison determines the result of the function because
1405 the extension character (or some character before it) is necessarily
1406 different from the character at the same offset in the other input
1410 For two sequences of digits, the number of leading zeros is counted (which
1411 can be zero). If the count differs, the string with more leading zeros
1412 in the digit sequence is considered smaller than the other string.
1415 If the two sequences of digits have no leading zeros, they are compared
1416 as integers, that is, the string with the longer digit sequence is
1417 deemed larger, and if both sequences are of equal length, they are
1418 compared lexicographically.
1421 If both digit sequences start with a zero and have an equal number of
1422 leading zeros, they are compared lexicographically if their lengths are
1423 the same. If the lengths differ, the shorter sequence is extended with
1424 the following character in its input string, and the other sequence is
1425 truncated to the same length, and both sequences are compared
1426 lexicographically (similar to the non-digit sequence case above).
1429 The treatment of leading zeros and the tie-breaking extension characters
1430 (which in effect propagate across non-digit/digit sequence boundaries)
1431 differs from other version-comparison algorithms.
1434 strverscmp ("no digit", "no digit")
1435 @result{} 0 /* @r{same behavior as strcmp.} */
1436 strverscmp ("item#99", "item#100")
1437 @result{} <0 /* @r{same prefix, but 99 < 100.} */
1438 strverscmp ("alpha1", "alpha001")
1439 @result{} >0 /* @r{different number of leading zeros (0 and 2).} */
1440 strverscmp ("part1_f012", "part1_f01")
1441 @result{} >0 /* @r{lexicographical comparison with leading zeros.} */
1442 strverscmp ("foo.009", "foo.0")
1443 @result{} <0 /* @r{different number of leading zeros (2 and 1).} */
1446 @code{strverscmp} is a GNU extension.
1451 @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
1452 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1453 This is an obsolete alias for @code{memcmp}, derived from BSD.
1456 @node Collation Functions
1457 @section Collation Functions
1459 @cindex collating strings
1460 @cindex string collation functions
1462 In some locales, the conventions for lexicographic ordering differ from
1463 the strict numeric ordering of character codes. For example, in Spanish
1464 most glyphs with diacritical marks such as accents are not considered
1465 distinct letters for the purposes of collation. On the other hand, the
1466 two-character sequence @samp{ll} is treated as a single letter that is
1467 collated immediately after @samp{l}.
1469 You can use the functions @code{strcoll} and @code{strxfrm} (declared in
1470 the headers file @file{string.h}) and @code{wcscoll} and @code{wcsxfrm}
1471 (declared in the headers file @file{wchar}) to compare strings using a
1472 collation ordering appropriate for the current locale. The locale used
1473 by these functions in particular can be specified by setting the locale
1474 for the @code{LC_COLLATE} category; see @ref{Locales}.
1478 In the standard C locale, the collation sequence for @code{strcoll} is
1479 the same as that for @code{strcmp}. Similarly, @code{wcscoll} and
1480 @code{wcscmp} are the same in this situation.
1482 Effectively, the way these functions work is by applying a mapping to
1483 transform the characters in a multibyte string to a byte
1484 sequence that represents
1485 the string's position in the collating sequence of the current locale.
1486 Comparing two such byte sequences in a simple fashion is equivalent to
1487 comparing the strings with the locale's collating sequence.
1489 The functions @code{strcoll} and @code{wcscoll} perform this translation
1490 implicitly, in order to do one comparison. By contrast, @code{strxfrm}
1491 and @code{wcsxfrm} perform the mapping explicitly. If you are making
1492 multiple comparisons using the same string or set of strings, it is
1493 likely to be more efficient to use @code{strxfrm} or @code{wcsxfrm} to
1494 transform all the strings just once, and subsequently compare the
1495 transformed strings with @code{strcmp} or @code{wcscmp}.
1499 @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
1500 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1501 @c Calls strcoll_l with the current locale, which dereferences only the
1502 @c LC_COLLATE data pointer.
1503 The @code{strcoll} function is similar to @code{strcmp} but uses the
1504 collating sequence of the current locale for collation (the
1505 @code{LC_COLLATE} locale). The arguments are multibyte strings.
1510 @deftypefun int wcscoll (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1511 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1512 @c Same as strcoll, but calling wcscoll_l.
1513 The @code{wcscoll} function is similar to @code{wcscmp} but uses the
1514 collating sequence of the current locale for collation (the
1515 @code{LC_COLLATE} locale).
1518 Here is an example of sorting an array of strings, using @code{strcoll}
1519 to compare them. The actual sort algorithm is not written here; it
1520 comes from @code{qsort} (@pxref{Array Sort Function}). The job of the
1521 code shown here is to say how to compare the strings while sorting them.
1522 (Later on in this section, we will show a way to do this more
1523 efficiently using @code{strxfrm}.)
1526 /* @r{This is the comparison function used with @code{qsort}.} */
1529 compare_elements (const void *v1, const void *v2)
1531 char * const *p1 = v1;
1532 char * const *p2 = v2;
1534 return strcoll (*p1, *p2);
1537 /* @r{This is the entry point---the function to sort}
1538 @r{strings using the locale's collating sequence.} */
1541 sort_strings (char **array, int nstrings)
1543 /* @r{Sort @code{temp_array} by comparing the strings.} */
1544 qsort (array, nstrings,
1545 sizeof (char *), compare_elements);
1549 @cindex converting string to collation order
1552 @deftypefun size_t strxfrm (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
1553 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1554 The function @code{strxfrm} transforms the multibyte string
1555 @var{from} using the
1556 collation transformation determined by the locale currently selected for
1557 collation, and stores the transformed string in the array @var{to}. Up
1558 to @var{size} bytes (including a terminating null byte) are
1561 The behavior is undefined if the strings @var{to} and @var{from}
1562 overlap; see @ref{Copying Strings and Arrays}.
1564 The return value is the length of the entire transformed string. This
1565 value is not affected by the value of @var{size}, but if it is greater
1566 or equal than @var{size}, it means that the transformed string did not
1567 entirely fit in the array @var{to}. In this case, only as much of the
1568 string as actually fits was stored. To get the whole transformed
1569 string, call @code{strxfrm} again with a bigger output array.
1571 The transformed string may be longer than the original string, and it
1572 may also be shorter.
1574 If @var{size} is zero, no bytes are stored in @var{to}. In this
1575 case, @code{strxfrm} simply returns the number of bytes that would
1576 be the length of the transformed string. This is useful for determining
1577 what size the allocated array should be. It does not matter what
1578 @var{to} is if @var{size} is zero; @var{to} may even be a null pointer.
1583 @deftypefun size_t wcsxfrm (wchar_t *restrict @var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
1584 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1585 The function @code{wcsxfrm} transforms wide string @var{wfrom}
1586 using the collation transformation determined by the locale currently
1587 selected for collation, and stores the transformed string in the array
1588 @var{wto}. Up to @var{size} wide characters (including a terminating null
1589 wide character) are stored.
1591 The behavior is undefined if the strings @var{wto} and @var{wfrom}
1592 overlap; see @ref{Copying Strings and Arrays}.
1594 The return value is the length of the entire transformed wide
1595 string. This value is not affected by the value of @var{size}, but if
1596 it is greater or equal than @var{size}, it means that the transformed
1597 wide string did not entirely fit in the array @var{wto}. In
1598 this case, only as much of the wide string as actually fits
1599 was stored. To get the whole transformed wide string, call
1600 @code{wcsxfrm} again with a bigger output array.
1602 The transformed wide string may be longer than the original
1603 wide string, and it may also be shorter.
1605 If @var{size} is zero, no wide characters are stored in @var{to}. In this
1606 case, @code{wcsxfrm} simply returns the number of wide characters that
1607 would be the length of the transformed wide string. This is
1608 useful for determining what size the allocated array should be (remember
1609 to multiply with @code{sizeof (wchar_t)}). It does not matter what
1610 @var{wto} is if @var{size} is zero; @var{wto} may even be a null pointer.
1613 Here is an example of how you can use @code{strxfrm} when
1614 you plan to do many comparisons. It does the same thing as the previous
1615 example, but much faster, because it has to transform each string only
1616 once, no matter how many times it is compared with other strings. Even
1617 the time needed to allocate and free storage is much less than the time
1618 we save, when there are many strings.
1621 struct sorter @{ char *input; char *transformed; @};
1623 /* @r{This is the comparison function used with @code{qsort}}
1624 @r{to sort an array of @code{struct sorter}.} */
1627 compare_elements (const void *v1, const void *v2)
1629 const struct sorter *p1 = v1;
1630 const struct sorter *p2 = v2;
1632 return strcmp (p1->transformed, p2->transformed);
1635 /* @r{This is the entry point---the function to sort}
1636 @r{strings using the locale's collating sequence.} */
1639 sort_strings_fast (char **array, int nstrings)
1641 struct sorter temp_array[nstrings];
1644 /* @r{Set up @code{temp_array}. Each element contains}
1645 @r{one input string and its transformed string.} */
1646 for (i = 0; i < nstrings; i++)
1648 size_t length = strlen (array[i]) * 2;
1650 size_t transformed_length;
1652 temp_array[i].input = array[i];
1654 /* @r{First try a buffer perhaps big enough.} */
1655 transformed = (char *) xmalloc (length);
1657 /* @r{Transform @code{array[i]}.} */
1658 transformed_length = strxfrm (transformed, array[i], length);
1660 /* @r{If the buffer was not large enough, resize it}
1661 @r{and try again.} */
1662 if (transformed_length >= length)
1664 /* @r{Allocate the needed space. +1 for terminating}
1665 @r{@code{'\0'} byte.} */
1666 transformed = (char *) xrealloc (transformed,
1667 transformed_length + 1);
1669 /* @r{The return value is not interesting because we know}
1670 @r{how long the transformed string is.} */
1671 (void) strxfrm (transformed, array[i],
1672 transformed_length + 1);
1675 temp_array[i].transformed = transformed;
1678 /* @r{Sort @code{temp_array} by comparing transformed strings.} */
1679 qsort (temp_array, nstrings,
1680 sizeof (struct sorter), compare_elements);
1682 /* @r{Put the elements back in the permanent array}
1683 @r{in their sorted order.} */
1684 for (i = 0; i < nstrings; i++)
1685 array[i] = temp_array[i].input;
1687 /* @r{Free the strings we allocated.} */
1688 for (i = 0; i < nstrings; i++)
1689 free (temp_array[i].transformed);
1693 The interesting part of this code for the wide character version would
1698 sort_strings_fast (wchar_t **array, int nstrings)
1701 /* @r{Transform @code{array[i]}.} */
1702 transformed_length = wcsxfrm (transformed, array[i], length);
1704 /* @r{If the buffer was not large enough, resize it}
1705 @r{and try again.} */
1706 if (transformed_length >= length)
1708 /* @r{Allocate the needed space. +1 for terminating}
1709 @r{@code{L'\0'} wide character.} */
1710 transformed = (wchar_t *) xrealloc (transformed,
1711 (transformed_length + 1)
1712 * sizeof (wchar_t));
1714 /* @r{The return value is not interesting because we know}
1715 @r{how long the transformed string is.} */
1716 (void) wcsxfrm (transformed, array[i],
1717 transformed_length + 1);
1723 Note the additional multiplication with @code{sizeof (wchar_t)} in the
1724 @code{realloc} call.
1726 @strong{Compatibility Note:} The string collation functions are a new
1727 feature of @w{ISO C90}. Older C dialects have no equivalent feature.
1728 The wide character versions were introduced in @w{Amendment 1} to @w{ISO
1731 @node Search Functions
1732 @section Search Functions
1734 This section describes library functions which perform various kinds
1735 of searching operations on strings and arrays. These functions are
1736 declared in the header file @file{string.h}.
1738 @cindex search functions (for strings)
1739 @cindex string search functions
1743 @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
1744 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1745 This function finds the first occurrence of the byte @var{c} (converted
1746 to an @code{unsigned char}) in the initial @var{size} bytes of the
1747 object beginning at @var{block}. The return value is a pointer to the
1748 located byte, or a null pointer if no match was found.
1753 @deftypefun {wchar_t *} wmemchr (const wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
1754 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1755 This function finds the first occurrence of the wide character @var{wc}
1756 in the initial @var{size} wide characters of the object beginning at
1757 @var{block}. The return value is a pointer to the located wide
1758 character, or a null pointer if no match was found.
1763 @deftypefun {void *} rawmemchr (const void *@var{block}, int @var{c})
1764 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1765 Often the @code{memchr} function is used with the knowledge that the
1766 byte @var{c} is available in the memory block specified by the
1767 parameters. But this means that the @var{size} parameter is not really
1768 needed and that the tests performed with it at runtime (to check whether
1769 the end of the block is reached) are not needed.
1771 The @code{rawmemchr} function exists for just this situation which is
1772 surprisingly frequent. The interface is similar to @code{memchr} except
1773 that the @var{size} parameter is missing. The function will look beyond
1774 the end of the block pointed to by @var{block} in case the programmer
1775 made an error in assuming that the byte @var{c} is present in the block.
1776 In this case the result is unspecified. Otherwise the return value is a
1777 pointer to the located byte.
1779 This function is of special interest when looking for the end of a
1780 string. Since all strings are terminated by a null byte a call like
1783 rawmemchr (str, '\0')
1787 will never go beyond the end of the string.
1789 This function is a GNU extension.
1794 @deftypefun {void *} memrchr (const void *@var{block}, int @var{c}, size_t @var{size})
1795 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1796 The function @code{memrchr} is like @code{memchr}, except that it searches
1797 backwards from the end of the block defined by @var{block} and @var{size}
1798 (instead of forwards from the front).
1800 This function is a GNU extension.
1805 @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
1806 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1807 The @code{strchr} function finds the first occurrence of the byte
1808 @var{c} (converted to a @code{char}) in the string
1809 beginning at @var{string}. The return value is a pointer to the located
1810 byte, or a null pointer if no match was found.
1814 strchr ("hello, world", 'l')
1815 @result{} "llo, world"
1816 strchr ("hello, world", '?')
1820 The terminating null byte is considered to be part of the string,
1821 so you can use this function get a pointer to the end of a string by
1822 specifying zero as the value of the @var{c} argument.
1824 When @code{strchr} returns a null pointer, it does not let you know
1825 the position of the terminating null byte it has found. If you
1826 need that information, it is better (but less portable) to use
1827 @code{strchrnul} than to search for it a second time.
1832 @deftypefun {wchar_t *} wcschr (const wchar_t *@var{wstring}, int @var{wc})
1833 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1834 The @code{wcschr} function finds the first occurrence of the wide
1835 character @var{wc} in the wide string
1836 beginning at @var{wstring}. The return value is a pointer to the
1837 located wide character, or a null pointer if no match was found.
1839 The terminating null wide character is considered to be part of the wide
1840 string, so you can use this function get a pointer to the end
1841 of a wide string by specifying a null wide character as the
1842 value of the @var{wc} argument. It would be better (but less portable)
1843 to use @code{wcschrnul} in this case, though.
1848 @deftypefun {char *} strchrnul (const char *@var{string}, int @var{c})
1849 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1850 @code{strchrnul} is the same as @code{strchr} except that if it does
1851 not find the byte, it returns a pointer to string's terminating
1852 null byte rather than a null pointer.
1854 This function is a GNU extension.
1859 @deftypefun {wchar_t *} wcschrnul (const wchar_t *@var{wstring}, wchar_t @var{wc})
1860 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1861 @code{wcschrnul} is the same as @code{wcschr} except that if it does not
1862 find the wide character, it returns a pointer to the wide string's
1863 terminating null wide character rather than a null pointer.
1865 This function is a GNU extension.
1868 One useful, but unusual, use of the @code{strchr}
1869 function is when one wants to have a pointer pointing to the null byte
1870 terminating a string. This is often written in this way:
1877 This is almost optimal but the addition operation duplicated a bit of
1878 the work already done in the @code{strlen} function. A better solution
1882 s = strchr (s, '\0');
1885 There is no restriction on the second parameter of @code{strchr} so it
1886 could very well also be zero. Those readers thinking very
1887 hard about this might now point out that the @code{strchr} function is
1888 more expensive than the @code{strlen} function since we have two abort
1889 criteria. This is right. But in @theglibc{} the implementation of
1890 @code{strchr} is optimized in a special way so that @code{strchr}
1895 @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
1896 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1897 The function @code{strrchr} is like @code{strchr}, except that it searches
1898 backwards from the end of the string @var{string} (instead of forwards
1903 strrchr ("hello, world", 'l')
1910 @deftypefun {wchar_t *} wcsrchr (const wchar_t *@var{wstring}, wchar_t @var{c})
1911 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1912 The function @code{wcsrchr} is like @code{wcschr}, except that it searches
1913 backwards from the end of the string @var{wstring} (instead of forwards
1919 @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
1920 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1921 This is like @code{strchr}, except that it searches @var{haystack} for a
1922 substring @var{needle} rather than just a single byte. It
1923 returns a pointer into the string @var{haystack} that is the first
1924 byte of the substring, or a null pointer if no match was found. If
1925 @var{needle} is an empty string, the function returns @var{haystack}.
1929 strstr ("hello, world", "l")
1930 @result{} "llo, world"
1931 strstr ("hello, world", "wo")
1938 @deftypefun {wchar_t *} wcsstr (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
1939 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1940 This is like @code{wcschr}, except that it searches @var{haystack} for a
1941 substring @var{needle} rather than just a single wide character. It
1942 returns a pointer into the string @var{haystack} that is the first wide
1943 character of the substring, or a null pointer if no match was found. If
1944 @var{needle} is an empty string, the function returns @var{haystack}.
1949 @deftypefun {wchar_t *} wcswcs (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
1950 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1951 @code{wcswcs} is a deprecated alias for @code{wcsstr}. This is the
1952 name originally used in the X/Open Portability Guide before the
1953 @w{Amendment 1} to @w{ISO C90} was published.
1959 @deftypefun {char *} strcasestr (const char *@var{haystack}, const char *@var{needle})
1960 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1961 @c There may be multiple calls of strncasecmp, each accessing the locale
1962 @c object independently.
1963 This is like @code{strstr}, except that it ignores case in searching for
1964 the substring. Like @code{strcasecmp}, it is locale dependent how
1965 uppercase and lowercase characters are related, and arguments are
1971 strcasestr ("hello, world", "L")
1972 @result{} "llo, world"
1973 strcasestr ("hello, World", "wo")
1981 @deftypefun {void *} memmem (const void *@var{haystack}, size_t @var{haystack-len},@*const void *@var{needle}, size_t @var{needle-len})
1982 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1983 This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
1984 arrays rather than strings. @var{needle-len} is the
1985 length of @var{needle} and @var{haystack-len} is the length of
1986 @var{haystack}.@refill
1988 This function is a GNU extension.
1993 @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
1994 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1995 The @code{strspn} (``string span'') function returns the length of the
1996 initial substring of @var{string} that consists entirely of bytes that
1997 are members of the set specified by the string @var{skipset}. The order
1998 of the bytes in @var{skipset} is not important.
2002 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
2006 In a multibyte string, characters consisting of
2007 more than one byte are not treated as single entities. Each byte is treated
2008 separately. The function is not locale-dependent.
2013 @deftypefun size_t wcsspn (const wchar_t *@var{wstring}, const wchar_t *@var{skipset})
2014 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2015 The @code{wcsspn} (``wide character string span'') function returns the
2016 length of the initial substring of @var{wstring} that consists entirely
2017 of wide characters that are members of the set specified by the string
2018 @var{skipset}. The order of the wide characters in @var{skipset} is not
2024 @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
2025 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2026 The @code{strcspn} (``string complement span'') function returns the length
2027 of the initial substring of @var{string} that consists entirely of bytes
2028 that are @emph{not} members of the set specified by the string @var{stopset}.
2029 (In other words, it returns the offset of the first byte in @var{string}
2030 that is a member of the set @var{stopset}.)
2034 strcspn ("hello, world", " \t\n,.;!?")
2038 In a multibyte string, characters consisting of
2039 more than one byte are not treated as a single entities. Each byte is treated
2040 separately. The function is not locale-dependent.
2045 @deftypefun size_t wcscspn (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
2046 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2047 The @code{wcscspn} (``wide character string complement span'') function
2048 returns the length of the initial substring of @var{wstring} that
2049 consists entirely of wide characters that are @emph{not} members of the
2050 set specified by the string @var{stopset}. (In other words, it returns
2051 the offset of the first wide character in @var{string} that is a member of
2052 the set @var{stopset}.)
2057 @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
2058 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2059 The @code{strpbrk} (``string pointer break'') function is related to
2060 @code{strcspn}, except that it returns a pointer to the first byte
2061 in @var{string} that is a member of the set @var{stopset} instead of the
2062 length of the initial substring. It returns a null pointer if no such
2063 byte from @var{stopset} is found.
2065 @c @group Invalid outside the example.
2069 strpbrk ("hello, world", " \t\n,.;!?")
2074 In a multibyte string, characters consisting of
2075 more than one byte are not treated as single entities. Each byte is treated
2076 separately. The function is not locale-dependent.
2081 @deftypefun {wchar_t *} wcspbrk (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
2082 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2083 The @code{wcspbrk} (``wide character string pointer break'') function is
2084 related to @code{wcscspn}, except that it returns a pointer to the first
2085 wide character in @var{wstring} that is a member of the set
2086 @var{stopset} instead of the length of the initial substring. It
2087 returns a null pointer if no such wide character from @var{stopset} is found.
2091 @subsection Compatibility String Search Functions
2095 @deftypefun {char *} index (const char *@var{string}, int @var{c})
2096 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2097 @code{index} is another name for @code{strchr}; they are exactly the same.
2098 New code should always use @code{strchr} since this name is defined in
2099 @w{ISO C} while @code{index} is a BSD invention which never was available
2100 on @w{System V} derived systems.
2105 @deftypefun {char *} rindex (const char *@var{string}, int @var{c})
2106 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2107 @code{rindex} is another name for @code{strrchr}; they are exactly the same.
2108 New code should always use @code{strrchr} since this name is defined in
2109 @w{ISO C} while @code{rindex} is a BSD invention which never was available
2110 on @w{System V} derived systems.
2113 @node Finding Tokens in a String
2114 @section Finding Tokens in a String
2116 @cindex tokenizing strings
2117 @cindex breaking a string into tokens
2118 @cindex parsing tokens from a string
2119 It's fairly common for programs to have a need to do some simple kinds
2120 of lexical analysis and parsing, such as splitting a command string up
2121 into tokens. You can do this with the @code{strtok} function, declared
2122 in the header file @file{string.h}.
2127 @deftypefun {char *} strtok (char *restrict @var{newstring}, const char *restrict @var{delimiters})
2128 @safety{@prelim{}@mtunsafe{@mtasurace{:strtok}}@asunsafe{}@acsafe{}}
2129 A string can be split into tokens by making a series of calls to the
2130 function @code{strtok}.
2132 The string to be split up is passed as the @var{newstring} argument on
2133 the first call only. The @code{strtok} function uses this to set up
2134 some internal state information. Subsequent calls to get additional
2135 tokens from the same string are indicated by passing a null pointer as
2136 the @var{newstring} argument. Calling @code{strtok} with another
2137 non-null @var{newstring} argument reinitializes the state information.
2138 It is guaranteed that no other library function ever calls @code{strtok}
2139 behind your back (which would mess up this internal state information).
2141 The @var{delimiters} argument is a string that specifies a set of delimiters
2142 that may surround the token being extracted. All the initial bytes
2143 that are members of this set are discarded. The first byte that is
2144 @emph{not} a member of this set of delimiters marks the beginning of the
2145 next token. The end of the token is found by looking for the next
2146 byte that is a member of the delimiter set. This byte in the
2147 original string @var{newstring} is overwritten by a null byte, and the
2148 pointer to the beginning of the token in @var{newstring} is returned.
2150 On the next call to @code{strtok}, the searching begins at the next
2151 byte beyond the one that marked the end of the previous token.
2152 Note that the set of delimiters @var{delimiters} do not have to be the
2153 same on every call in a series of calls to @code{strtok}.
2155 If the end of the string @var{newstring} is reached, or if the remainder of
2156 string consists only of delimiter bytes, @code{strtok} returns
2159 In a multibyte string, characters consisting of
2160 more than one byte are not treated as single entities. Each byte is treated
2161 separately. The function is not locale-dependent.
2166 @deftypefun {wchar_t *} wcstok (wchar_t *@var{newstring}, const wchar_t *@var{delimiters}, wchar_t **@var{save_ptr})
2167 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2168 A string can be split into tokens by making a series of calls to the
2169 function @code{wcstok}.
2171 The string to be split up is passed as the @var{newstring} argument on
2172 the first call only. The @code{wcstok} function uses this to set up
2173 some internal state information. Subsequent calls to get additional
2174 tokens from the same wide string are indicated by passing a
2175 null pointer as the @var{newstring} argument, which causes the pointer
2176 previously stored in @var{save_ptr} to be used instead.
2178 The @var{delimiters} argument is a wide string that specifies
2179 a set of delimiters that may surround the token being extracted. All
2180 the initial wide characters that are members of this set are discarded.
2181 The first wide character that is @emph{not} a member of this set of
2182 delimiters marks the beginning of the next token. The end of the token
2183 is found by looking for the next wide character that is a member of the
2184 delimiter set. This wide character in the original wide
2185 string @var{newstring} is overwritten by a null wide character, the
2186 pointer past the overwritten wide character is saved in @var{save_ptr},
2187 and the pointer to the beginning of the token in @var{newstring} is
2190 On the next call to @code{wcstok}, the searching begins at the next
2191 wide character beyond the one that marked the end of the previous token.
2192 Note that the set of delimiters @var{delimiters} do not have to be the
2193 same on every call in a series of calls to @code{wcstok}.
2195 If the end of the wide string @var{newstring} is reached, or
2196 if the remainder of string consists only of delimiter wide characters,
2197 @code{wcstok} returns a null pointer.
2200 @strong{Warning:} Since @code{strtok} and @code{wcstok} alter the string
2201 they is parsing, you should always copy the string to a temporary buffer
2202 before parsing it with @code{strtok}/@code{wcstok} (@pxref{Copying Strings
2203 and Arrays}). If you allow @code{strtok} or @code{wcstok} to modify
2204 a string that came from another part of your program, you are asking for
2205 trouble; that string might be used for other purposes after
2206 @code{strtok} or @code{wcstok} has modified it, and it would not have
2209 The string that you are operating on might even be a constant. Then
2210 when @code{strtok} or @code{wcstok} tries to modify it, your program
2211 will get a fatal signal for writing in read-only memory. @xref{Program
2212 Error Signals}. Even if the operation of @code{strtok} or @code{wcstok}
2213 would not require a modification of the string (e.g., if there is
2214 exactly one token) the string can (and in the @glibcadj{} case will) be
2217 This is a special case of a general principle: if a part of a program
2218 does not have as its purpose the modification of a certain data
2219 structure, then it is error-prone to modify the data structure
2222 The function @code{strtok} is not reentrant, whereas @code{wcstok} is.
2223 @xref{Nonreentrancy}, for a discussion of where and why reentrancy is
2226 Here is a simple example showing the use of @code{strtok}.
2228 @comment Yes, this example has been tested.
2235 const char string[] = "words separated by spaces -- and, punctuation!";
2236 const char delimiters[] = " .,;:!-";
2241 cp = strdupa (string); /* Make writable copy. */
2242 token = strtok (cp, delimiters); /* token => "words" */
2243 token = strtok (NULL, delimiters); /* token => "separated" */
2244 token = strtok (NULL, delimiters); /* token => "by" */
2245 token = strtok (NULL, delimiters); /* token => "spaces" */
2246 token = strtok (NULL, delimiters); /* token => "and" */
2247 token = strtok (NULL, delimiters); /* token => "punctuation" */
2248 token = strtok (NULL, delimiters); /* token => NULL */
2251 @Theglibc{} contains two more functions for tokenizing a string
2252 which overcome the limitation of non-reentrancy. They are not
2253 available available for wide strings.
2257 @deftypefun {char *} strtok_r (char *@var{newstring}, const char *@var{delimiters}, char **@var{save_ptr})
2258 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2259 Just like @code{strtok}, this function splits the string into several
2260 tokens which can be accessed by successive calls to @code{strtok_r}.
2261 The difference is that, as in @code{wcstok}, the information about the
2262 next token is stored in the space pointed to by the third argument,
2263 @var{save_ptr}, which is a pointer to a string pointer. Calling
2264 @code{strtok_r} with a null pointer for @var{newstring} and leaving
2265 @var{save_ptr} between the calls unchanged does the job without
2266 hindering reentrancy.
2268 This function is defined in POSIX.1 and can be found on many systems
2269 which support multi-threading.
2274 @deftypefun {char *} strsep (char **@var{string_ptr}, const char *@var{delimiter})
2275 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2276 This function has a similar functionality as @code{strtok_r} with the
2277 @var{newstring} argument replaced by the @var{save_ptr} argument. The
2278 initialization of the moving pointer has to be done by the user.
2279 Successive calls to @code{strsep} move the pointer along the tokens
2280 separated by @var{delimiter}, returning the address of the next token
2281 and updating @var{string_ptr} to point to the beginning of the next
2284 One difference between @code{strsep} and @code{strtok_r} is that if the
2285 input string contains more than one byte from @var{delimiter} in a
2286 row @code{strsep} returns an empty string for each pair of bytes
2287 from @var{delimiter}. This means that a program normally should test
2288 for @code{strsep} returning an empty string before processing it.
2290 This function was introduced in 4.3BSD and therefore is widely available.
2293 Here is how the above example looks like when @code{strsep} is used.
2295 @comment Yes, this example has been tested.
2302 const char string[] = "words separated by spaces -- and, punctuation!";
2303 const char delimiters[] = " .,;:!-";
2309 running = strdupa (string);
2310 token = strsep (&running, delimiters); /* token => "words" */
2311 token = strsep (&running, delimiters); /* token => "separated" */
2312 token = strsep (&running, delimiters); /* token => "by" */
2313 token = strsep (&running, delimiters); /* token => "spaces" */
2314 token = strsep (&running, delimiters); /* token => "" */
2315 token = strsep (&running, delimiters); /* token => "" */
2316 token = strsep (&running, delimiters); /* token => "" */
2317 token = strsep (&running, delimiters); /* token => "and" */
2318 token = strsep (&running, delimiters); /* token => "" */
2319 token = strsep (&running, delimiters); /* token => "punctuation" */
2320 token = strsep (&running, delimiters); /* token => "" */
2321 token = strsep (&running, delimiters); /* token => NULL */
2326 @deftypefun {char *} basename (const char *@var{filename})
2327 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2328 The GNU version of the @code{basename} function returns the last
2329 component of the path in @var{filename}. This function is the preferred
2330 usage, since it does not modify the argument, @var{filename}, and
2331 respects trailing slashes. The prototype for @code{basename} can be
2332 found in @file{string.h}. Note, this function is overridden by the XPG
2333 version, if @file{libgen.h} is included.
2335 Example of using GNU @code{basename}:
2341 main (int argc, char *argv[])
2343 char *prog = basename (argv[0]);
2347 fprintf (stderr, "Usage %s <arg>\n", prog);
2355 @strong{Portability Note:} This function may produce different results
2356 on different systems.
2362 @deftypefun {char *} basename (char *@var{path})
2363 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2364 This is the standard XPG defined @code{basename}. It is similar in
2365 spirit to the GNU version, but may modify the @var{path} by removing
2366 trailing '/' bytes. If the @var{path} is made up entirely of '/'
2367 bytes, then "/" will be returned. Also, if @var{path} is
2368 @code{NULL} or an empty string, then "." is returned. The prototype for
2369 the XPG version can be found in @file{libgen.h}.
2371 Example of using XPG @code{basename}:
2377 main (int argc, char *argv[])
2380 char *path = strdupa (argv[0]);
2382 prog = basename (path);
2386 fprintf (stderr, "Usage %s <arg>\n", prog);
2398 @deftypefun {char *} dirname (char *@var{path})
2399 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2400 The @code{dirname} function is the compliment to the XPG version of
2401 @code{basename}. It returns the parent directory of the file specified
2402 by @var{path}. If @var{path} is @code{NULL}, an empty string, or
2403 contains no '/' bytes, then "." is returned. The prototype for this
2404 function can be found in @file{libgen.h}.
2410 The function below addresses the perennial programming quandary: ``How do
2411 I take good data in string form and painlessly turn it into garbage?''
2412 This is actually a fairly simple task for C programmers who do not use
2413 @theglibc{} string functions, but for programs based on @theglibc{},
2414 the @code{strfry} function is the preferred method for
2415 destroying string data.
2417 The prototype for this function is in @file{string.h}.
2421 @deftypefun {char *} strfry (char *@var{string})
2422 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2423 @c Calls initstate_r, time, getpid, strlen, and random_r.
2425 @code{strfry} creates a pseudorandom anagram of a string, replacing the
2426 input with the anagram in place. For each position in the string,
2427 @code{strfry} swaps it with a position in the string selected at random
2428 (from a uniform distribution). The two positions may be the same.
2430 The return value of @code{strfry} is always @var{string}.
2432 @strong{Portability Note:} This function is unique to @theglibc{}.
2437 @node Trivial Encryption
2438 @section Trivial Encryption
2442 The @code{memfrob} function converts an array of data to something
2443 unrecognizable and back again. It is not encryption in its usual sense
2444 since it is easy for someone to convert the encrypted data back to clear
2445 text. The transformation is analogous to Usenet's ``Rot13'' encryption
2446 method for obscuring offensive jokes from sensitive eyes and such.
2447 Unlike Rot13, @code{memfrob} works on arbitrary binary data, not just
2451 For true encryption, @xref{Cryptographic Functions}.
2453 This function is declared in @file{string.h}.
2458 @deftypefun {void *} memfrob (void *@var{mem}, size_t @var{length})
2459 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2461 @code{memfrob} transforms (frobnicates) each byte of the data structure
2462 at @var{mem}, which is @var{length} bytes long, by bitwise exclusive
2463 oring it with binary 00101010. It does the transformation in place and
2464 its return value is always @var{mem}.
2466 Note that @code{memfrob} a second time on the same data structure
2467 returns it to its original state.
2469 This is a good function for hiding information from someone who doesn't
2470 want to see it or doesn't want to see it very much. To really prevent
2471 people from retrieving the information, use stronger encryption such as
2472 that described in @xref{Cryptographic Functions}.
2474 @strong{Portability Note:} This function is unique to @theglibc{}.
2478 @node Encode Binary Data
2479 @section Encode Binary Data
2481 To store or transfer binary data in environments which only support text
2482 one has to encode the binary data by mapping the input bytes to
2483 bytes in the range allowed for storing or transferring. SVID
2484 systems (and nowadays XPG compliant systems) provide minimal support for
2489 @deftypefun {char *} l64a (long int @var{n})
2490 @safety{@prelim{}@mtunsafe{@mtasurace{:l64a}}@asunsafe{}@acsafe{}}
2491 This function encodes a 32-bit input value using bytes from the
2492 basic character set. It returns a pointer to a 7 byte buffer which
2493 contains an encoded version of @var{n}. To encode a series of bytes the
2494 user must copy the returned string to a destination buffer. It returns
2495 the empty string if @var{n} is zero, which is somewhat bizarre but
2496 mandated by the standard.@*
2497 @strong{Warning:} Since a static buffer is used this function should not
2498 be used in multi-threaded programs. There is no thread-safe alternative
2499 to this function in the C library.@*
2500 @strong{Compatibility Note:} The XPG standard states that the return
2501 value of @code{l64a} is undefined if @var{n} is negative. In the GNU
2502 implementation, @code{l64a} treats its argument as unsigned, so it will
2503 return a sensible encoding for any nonzero @var{n}; however, portable
2504 programs should not rely on this.
2506 To encode a large buffer @code{l64a} must be called in a loop, once for
2507 each 32-bit word of the buffer. For example, one could do something
2512 encode (const void *buf, size_t len)
2514 /* @r{We know in advance how long the buffer has to be.} */
2515 unsigned char *in = (unsigned char *) buf;
2516 char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
2519 /* @r{Encode the length.} */
2520 /* @r{Using `htonl' is necessary so that the data can be}
2521 @r{decoded even on machines with different byte order.}
2522 @r{`l64a' can return a string shorter than 6 bytes, so }
2523 @r{we pad it with encoding of 0 (}'.'@r{) at the end by }
2526 p = stpcpy (cp, l64a (htonl (len)));
2527 cp = mempcpy (p, "......", 6 - (p - cp));
2531 unsigned long int n = *in++;
2532 n = (n << 8) | *in++;
2533 n = (n << 8) | *in++;
2534 n = (n << 8) | *in++;
2536 p = stpcpy (cp, l64a (htonl (n)));
2537 cp = mempcpy (p, "......", 6 - (p - cp));
2541 unsigned long int n = *in++;
2544 n = (n << 8) | *in++;
2548 cp = stpcpy (cp, l64a (htonl (n)));
2555 It is strange that the library does not provide the complete
2556 functionality needed but so be it.
2560 To decode data produced with @code{l64a} the following function should be
2565 @deftypefun {long int} a64l (const char *@var{string})
2566 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2567 The parameter @var{string} should contain a string which was produced by
2568 a call to @code{l64a}. The function processes at least 6 bytes of
2569 this string, and decodes the bytes it finds according to the table
2570 below. It stops decoding when it finds a byte not in the table,
2571 rather like @code{atoi}; if you have a buffer which has been broken into
2572 lines, you must be careful to skip over the end-of-line bytes.
2574 The decoded number is returned as a @code{long int} value.
2577 The @code{l64a} and @code{a64l} functions use a base 64 encoding, in
2578 which each byte of an encoded string represents six bits of an
2579 input word. These symbols are used for the base 64 digits:
2581 @multitable {xxxxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx}
2582 @item @tab 0 @tab 1 @tab 2 @tab 3 @tab 4 @tab 5 @tab 6 @tab 7
2583 @item 0 @tab @code{.} @tab @code{/} @tab @code{0} @tab @code{1}
2584 @tab @code{2} @tab @code{3} @tab @code{4} @tab @code{5}
2585 @item 8 @tab @code{6} @tab @code{7} @tab @code{8} @tab @code{9}
2586 @tab @code{A} @tab @code{B} @tab @code{C} @tab @code{D}
2587 @item 16 @tab @code{E} @tab @code{F} @tab @code{G} @tab @code{H}
2588 @tab @code{I} @tab @code{J} @tab @code{K} @tab @code{L}
2589 @item 24 @tab @code{M} @tab @code{N} @tab @code{O} @tab @code{P}
2590 @tab @code{Q} @tab @code{R} @tab @code{S} @tab @code{T}
2591 @item 32 @tab @code{U} @tab @code{V} @tab @code{W} @tab @code{X}
2592 @tab @code{Y} @tab @code{Z} @tab @code{a} @tab @code{b}
2593 @item 40 @tab @code{c} @tab @code{d} @tab @code{e} @tab @code{f}
2594 @tab @code{g} @tab @code{h} @tab @code{i} @tab @code{j}
2595 @item 48 @tab @code{k} @tab @code{l} @tab @code{m} @tab @code{n}
2596 @tab @code{o} @tab @code{p} @tab @code{q} @tab @code{r}
2597 @item 56 @tab @code{s} @tab @code{t} @tab @code{u} @tab @code{v}
2598 @tab @code{w} @tab @code{x} @tab @code{y} @tab @code{z}
2601 This encoding scheme is not standard. There are some other encoding
2602 methods which are much more widely used (UU encoding, MIME encoding).
2603 Generally, it is better to use one of these encodings.
2605 @node Argz and Envz Vectors
2606 @section Argz and Envz Vectors
2608 @cindex argz vectors (string vectors)
2609 @cindex string vectors, null-byte separated
2610 @cindex argument vectors, null-byte separated
2611 @dfn{argz vectors} are vectors of strings in a contiguous block of
2612 memory, each element separated from its neighbors by null bytes
2615 @cindex envz vectors (environment vectors)
2616 @cindex environment vectors, null-byte separated
2617 @dfn{Envz vectors} are an extension of argz vectors where each element is a
2618 name-value pair, separated by a @code{'='} byte (as in a Unix
2622 * Argz Functions:: Operations on argz vectors.
2623 * Envz Functions:: Additional operations on environment vectors.
2626 @node Argz Functions, Envz Functions, , Argz and Envz Vectors
2627 @subsection Argz Functions
2629 Each argz vector is represented by a pointer to the first element, of
2630 type @code{char *}, and a size, of type @code{size_t}, both of which can
2631 be initialized to @code{0} to represent an empty argz vector. All argz
2632 functions accept either a pointer and a size argument, or pointers to
2633 them, if they will be modified.
2635 The argz functions use @code{malloc}/@code{realloc} to allocate/grow
2636 argz vectors, and so any argz vector created using these functions may
2637 be freed by using @code{free}; conversely, any argz function that may
2638 grow a string expects that string to have been allocated using
2639 @code{malloc} (those argz functions that only examine their arguments or
2640 modify them in place will work on any sort of memory).
2641 @xref{Unconstrained Allocation}.
2643 All argz functions that do memory allocation have a return type of
2644 @code{error_t}, and return @code{0} for success, and @code{ENOMEM} if an
2645 allocation error occurs.
2648 These functions are declared in the standard include file @file{argz.h}.
2652 @deftypefun {error_t} argz_create (char *const @var{argv}[], char **@var{argz}, size_t *@var{argz_len})
2653 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2654 The @code{argz_create} function converts the Unix-style argument vector
2655 @var{argv} (a vector of pointers to normal C strings, terminated by
2656 @code{(char *)0}; @pxref{Program Arguments}) into an argz vector with
2657 the same elements, which is returned in @var{argz} and @var{argz_len}.
2662 @deftypefun {error_t} argz_create_sep (const char *@var{string}, int @var{sep}, char **@var{argz}, size_t *@var{argz_len})
2663 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2664 The @code{argz_create_sep} function converts the string
2665 @var{string} into an argz vector (returned in @var{argz} and
2666 @var{argz_len}) by splitting it into elements at every occurrence of the
2672 @deftypefun {size_t} argz_count (const char *@var{argz}, size_t @var{argz_len})
2673 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2674 Returns the number of elements in the argz vector @var{argz} and
2680 @deftypefun {void} argz_extract (const char *@var{argz}, size_t @var{argz_len}, char **@var{argv})
2681 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2682 The @code{argz_extract} function converts the argz vector @var{argz} and
2683 @var{argz_len} into a Unix-style argument vector stored in @var{argv},
2684 by putting pointers to every element in @var{argz} into successive
2685 positions in @var{argv}, followed by a terminator of @code{0}.
2686 @var{Argv} must be pre-allocated with enough space to hold all the
2687 elements in @var{argz} plus the terminating @code{(char *)0}
2688 (@code{(argz_count (@var{argz}, @var{argz_len}) + 1) * sizeof (char *)}
2689 bytes should be enough). Note that the string pointers stored into
2690 @var{argv} point into @var{argz}---they are not copies---and so
2691 @var{argz} must be copied if it will be changed while @var{argv} is
2692 still active. This function is useful for passing the elements in
2693 @var{argz} to an exec function (@pxref{Executing a File}).
2698 @deftypefun {void} argz_stringify (char *@var{argz}, size_t @var{len}, int @var{sep})
2699 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2700 The @code{argz_stringify} converts @var{argz} into a normal string with
2701 the elements separated by the byte @var{sep}, by replacing each
2702 @code{'\0'} inside @var{argz} (except the last one, which terminates the
2703 string) with @var{sep}. This is handy for printing @var{argz} in a
2709 @deftypefun {error_t} argz_add (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str})
2710 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2711 @c Calls strlen and argz_append.
2712 The @code{argz_add} function adds the string @var{str} to the end of the
2713 argz vector @code{*@var{argz}}, and updates @code{*@var{argz}} and
2714 @code{*@var{argz_len}} accordingly.
2719 @deftypefun {error_t} argz_add_sep (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str}, int @var{delim})
2720 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2721 The @code{argz_add_sep} function is similar to @code{argz_add}, but
2722 @var{str} is split into separate elements in the result at occurrences of
2723 the byte @var{delim}. This is useful, for instance, for
2724 adding the components of a Unix search path to an argz vector, by using
2725 a value of @code{':'} for @var{delim}.
2730 @deftypefun {error_t} argz_append (char **@var{argz}, size_t *@var{argz_len}, const char *@var{buf}, size_t @var{buf_len})
2731 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2732 The @code{argz_append} function appends @var{buf_len} bytes starting at
2733 @var{buf} to the argz vector @code{*@var{argz}}, reallocating
2734 @code{*@var{argz}} to accommodate it, and adding @var{buf_len} to
2735 @code{*@var{argz_len}}.
2740 @deftypefun {void} argz_delete (char **@var{argz}, size_t *@var{argz_len}, char *@var{entry})
2741 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2742 @c Calls free if no argument is left.
2743 If @var{entry} points to the beginning of one of the elements in the
2744 argz vector @code{*@var{argz}}, the @code{argz_delete} function will
2745 remove this entry and reallocate @code{*@var{argz}}, modifying
2746 @code{*@var{argz}} and @code{*@var{argz_len}} accordingly. Note that as
2747 destructive argz functions usually reallocate their argz argument,
2748 pointers into argz vectors such as @var{entry} will then become invalid.
2753 @deftypefun {error_t} argz_insert (char **@var{argz}, size_t *@var{argz_len}, char *@var{before}, const char *@var{entry})
2754 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2755 @c Calls argz_add or realloc and memmove.
2756 The @code{argz_insert} function inserts the string @var{entry} into the
2757 argz vector @code{*@var{argz}} at a point just before the existing
2758 element pointed to by @var{before}, reallocating @code{*@var{argz}} and
2759 updating @code{*@var{argz}} and @code{*@var{argz_len}}. If @var{before}
2760 is @code{0}, @var{entry} is added to the end instead (as if by
2761 @code{argz_add}). Since the first element is in fact the same as
2762 @code{*@var{argz}}, passing in @code{*@var{argz}} as the value of
2763 @var{before} will result in @var{entry} being inserted at the beginning.
2768 @deftypefun {char *} argz_next (const char *@var{argz}, size_t @var{argz_len}, const char *@var{entry})
2769 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2770 The @code{argz_next} function provides a convenient way of iterating
2771 over the elements in the argz vector @var{argz}. It returns a pointer
2772 to the next element in @var{argz} after the element @var{entry}, or
2773 @code{0} if there are no elements following @var{entry}. If @var{entry}
2774 is @code{0}, the first element of @var{argz} is returned.
2776 This behavior suggests two styles of iteration:
2780 while ((entry = argz_next (@var{argz}, @var{argz_len}, entry)))
2784 (the double parentheses are necessary to make some C compilers shut up
2785 about what they consider a questionable @code{while}-test) and:
2789 for (entry = @var{argz};
2791 entry = argz_next (@var{argz}, @var{argz_len}, entry))
2795 Note that the latter depends on @var{argz} having a value of @code{0} if
2796 it is empty (rather than a pointer to an empty block of memory); this
2797 invariant is maintained for argz vectors created by the functions here.
2802 @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}})
2803 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2804 Replace any occurrences of the string @var{str} in @var{argz} with
2805 @var{with}, reallocating @var{argz} as necessary. If
2806 @var{replace_count} is non-zero, @code{*@var{replace_count}} will be
2807 incremented by the number of replacements performed.
2810 @node Envz Functions, , Argz Functions, Argz and Envz Vectors
2811 @subsection Envz Functions
2813 Envz vectors are just argz vectors with additional constraints on the form
2814 of each element; as such, argz functions can also be used on them, where it
2817 Each element in an envz vector is a name-value pair, separated by a @code{'='}
2818 byte; if multiple @code{'='} bytes are present in an element, those
2819 after the first are considered part of the value, and treated like all other
2820 non-@code{'\0'} bytes.
2822 If @emph{no} @code{'='} bytes are present in an element, that element is
2823 considered the name of a ``null'' entry, as distinct from an entry with an
2824 empty value: @code{envz_get} will return @code{0} if given the name of null
2825 entry, whereas an entry with an empty value would result in a value of
2826 @code{""}; @code{envz_entry} will still find such entries, however. Null
2827 entries can be removed with the @code{envz_strip} function.
2829 As with argz functions, envz functions that may allocate memory (and thus
2830 fail) have a return type of @code{error_t}, and return either @code{0} or
2834 These functions are declared in the standard include file @file{envz.h}.
2838 @deftypefun {char *} envz_entry (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
2839 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2840 The @code{envz_entry} function finds the entry in @var{envz} with the name
2841 @var{name}, and returns a pointer to the whole entry---that is, the argz
2842 element which begins with @var{name} followed by a @code{'='} byte. If
2843 there is no entry with that name, @code{0} is returned.
2848 @deftypefun {char *} envz_get (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
2849 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2850 The @code{envz_get} function finds the entry in @var{envz} with the name
2851 @var{name} (like @code{envz_entry}), and returns a pointer to the value
2852 portion of that entry (following the @code{'='}). If there is no entry with
2853 that name (or only a null entry), @code{0} is returned.
2858 @deftypefun {error_t} envz_add (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name}, const char *@var{value})
2859 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2860 @c Calls envz_remove, which calls enz_entry and argz_delete, and then
2861 @c argz_add or equivalent code that reallocs and appends name=value.
2862 The @code{envz_add} function adds an entry to @code{*@var{envz}}
2863 (updating @code{*@var{envz}} and @code{*@var{envz_len}}) with the name
2864 @var{name}, and value @var{value}. If an entry with the same name
2865 already exists in @var{envz}, it is removed first. If @var{value} is
2866 @code{0}, then the new entry will be the special null type of entry
2872 @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})
2873 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2874 The @code{envz_merge} function adds each entry in @var{envz2} to @var{envz},
2875 as if with @code{envz_add}, updating @code{*@var{envz}} and
2876 @code{*@var{envz_len}}. If @var{override} is true, then values in @var{envz2}
2877 will supersede those with the same name in @var{envz}, otherwise not.
2879 Null entries are treated just like other entries in this respect, so a null
2880 entry in @var{envz} can prevent an entry of the same name in @var{envz2} from
2881 being added to @var{envz}, if @var{override} is false.
2886 @deftypefun {void} envz_strip (char **@var{envz}, size_t *@var{envz_len})
2887 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2888 The @code{envz_strip} function removes any null entries from @var{envz},
2889 updating @code{*@var{envz}} and @code{*@var{envz_len}}.
2894 @deftypefun {void} envz_remove (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name})
2895 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2896 The @code{envz_remove} function removes an entry named @var{name} from
2897 @var{envz}, updating @code{*@var{envz}} and @code{*@var{envz_len}}.
2900 @c FIXME this are undocumented:
2901 @c strcasecmp_l @safety{@mtsafe{}@assafe{}@acsafe{}} see strcasecmp