]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/string.texi
* manual/string.texi (wcstok): Fix prototype.
[thirdparty/glibc.git] / manual / string.texi
CommitLineData
390955cb 1@node String and Array Utilities, Character Set Handling, Character Handling, Top
7a68c94a 2@c %MENU% Utilities for copying and comparing strings and arrays
28f540f4
RM
3@chapter String and Array Utilities
4
5Operations on strings (or arrays of characters) are an important part of
1f77f049 6many programs. @Theglibc{} provides an extensive set of string
28f540f4
RM
7utility functions, including functions for copying, concatenating,
8comparing, and searching strings. Many of these functions can also
9operate on arbitrary regions of storage; for example, the @code{memcpy}
a5113b14 10function can be used to copy the contents of any kind of array.
28f540f4
RM
11
12It's fairly common for beginning C programmers to ``reinvent the wheel''
13by duplicating this functionality in their own code, but it pays to
14become familiar with the library functions and to make use of them,
15since this offers benefits in maintenance, efficiency, and portability.
16
17For instance, you could easily compare one string to another in two
18lines of C code, but if you use the built-in @code{strcmp} function,
19you're less likely to make a mistake. And, since these library
20functions are typically highly optimized, your program may run faster
21too.
22
23@menu
24* Representation of Strings:: Introduction to basic concepts.
25* String/Array Conventions:: Whether to use a string function or an
26 arbitrary array function.
27* String Length:: Determining the length of a string.
28* Copying and Concatenation:: Functions to copy the contents of strings
29 and arrays.
30* String/Array Comparison:: Functions for byte-wise and character-wise
31 comparison.
32* Collation Functions:: Functions for collating strings.
33* Search Functions:: Searching for a specific element or substring.
34* Finding Tokens in a String:: Splitting a string into tokens by looking
35 for delimiters.
0e4ee106
UD
36* strfry:: Function for flash-cooking a string.
37* Trivial Encryption:: Obscuring data.
b4012b75 38* Encode Binary Data:: Encoding and Decoding of Binary Data.
b13927da 39* Argz and Envz Vectors:: Null-separated string vectors.
28f540f4
RM
40@end menu
41
b4012b75 42@node Representation of Strings
28f540f4
RM
43@section Representation of Strings
44@cindex string, representation of
45
46This section is a quick summary of string concepts for beginning C
47programmers. It describes how character strings are represented in C
48and some common pitfalls. If you are already familiar with this
49material, you can skip this section.
50
51@cindex string
8a2f1f5b 52@cindex multibyte character string
28f540f4
RM
53A @dfn{string} is an array of @code{char} objects. But string-valued
54variables are usually declared to be pointers of type @code{char *}.
55Such variables do not include space for the text of a string; that has
56to be stored somewhere else---in an array variable, a string constant,
57or dynamically allocated memory (@pxref{Memory Allocation}). It's up to
58you to store the address of the chosen memory space into the pointer
59variable. Alternatively you can store a @dfn{null pointer} in the
60pointer variable. The null pointer does not point anywhere, so
61attempting to reference the string it points to gets an error.
62
8a2f1f5b
UD
63@cindex wide character string
64``string'' normally refers to multibyte character strings as opposed to
65wide character strings. Wide character strings are arrays of type
66@code{wchar_t} and as for multibyte character strings usually pointers
67of type @code{wchar_t *} are used.
68
69@cindex null character
70@cindex null wide character
28f540f4 71By convention, a @dfn{null character}, @code{'\0'}, marks the end of a
8a2f1f5b
UD
72multibyte character string and the @dfn{null wide character},
73@code{L'\0'}, marks the end of a wide character string. For example, in
74testing to see whether the @code{char *} variable @var{p} points to a
75null character marking the end of a string, you can write
76@code{!*@var{p}} or @code{*@var{p} == '\0'}.
28f540f4
RM
77
78A null character is quite different conceptually from a null pointer,
79although both are represented by the integer @code{0}.
80
81@cindex string literal
82@dfn{String literals} appear in C program source as strings of
8a2f1f5b
UD
83characters between double-quote characters (@samp{"}) where the initial
84double-quote character is immediately preceded by a capital @samp{L}
85(ell) character (as in @code{L"foo"}). In @w{ISO C}, string literals
86can also be formed by @dfn{string concatenation}: @code{"a" "b"} is the
87same as @code{"ab"}. For wide character strings one can either use
88@code{L"a" L"b"} or @code{L"a" "b"}. Modification of string literals is
89not allowed by the GNU C compiler, because literals are placed in
90read-only storage.
28f540f4
RM
91
92Character arrays that are declared @code{const} cannot be modified
93either. It's generally good style to declare non-modifiable string
94pointers to be of type @code{const char *}, since this often allows the
95C compiler to detect accidental modifications as well as providing some
96amount of documentation about what your program intends to do with the
97string.
98
99The amount of memory allocated for the character array may extend past
100the null character that normally marks the end of the string. In this
dd7d45e8 101document, the term @dfn{allocated size} is always used to refer to the
28f540f4
RM
102total amount of memory allocated for the string, while the term
103@dfn{length} refers to the number of characters up to (but not
104including) the terminating null character.
105@cindex length of string
106@cindex allocation size of string
107@cindex size of string
108@cindex string length
109@cindex string allocation
110
111A notorious source of program bugs is trying to put more characters in a
112string than fit in its allocated size. When writing code that extends
113strings or moves characters into a pre-allocated array, you should be
114very careful to keep track of the length of the text and make explicit
115checks for overflowing the array. Many of the library functions
116@emph{do not} do this for you! Remember also that you need to allocate
117an extra byte to hold the null character that marks the end of the
118string.
119
8a2f1f5b
UD
120@cindex single-byte string
121@cindex multibyte string
122Originally strings were sequences of bytes where each byte represents a
123single character. This is still true today if the strings are encoded
124using a single-byte character encoding. Things are different if the
125strings are encoded using a multibyte encoding (for more information on
126encodings see @ref{Extended Char Intro}). There is no difference in
127the programming interface for these two kind of strings; the programmer
128has to be aware of this and interpret the byte sequences accordingly.
129
130But since there is no separate interface taking care of these
131differences the byte-based string functions are sometimes hard to use.
132Since the count parameters of these functions specify bytes a call to
133@code{strncpy} could cut a multibyte character in the middle and put an
134incomplete (and therefore unusable) byte sequence in the target buffer.
135
136@cindex wide character string
137To avoid these problems later versions of the @w{ISO C} standard
138introduce a second set of functions which are operating on @dfn{wide
139characters} (@pxref{Extended Char Intro}). These functions don't have
140the problems the single-byte versions have since every wide character is
141a legal, interpretable value. This does not mean that cutting wide
142character strings at arbitrary points is without problems. It normally
143is for alphabet-based languages (except for non-normalized text) but
144languages based on syllables still have the problem that more than one
145wide character is necessary to complete a logical unit. This is a
146higher level problem which the @w{C library} functions are not designed
147to solve. But it is at least good that no invalid byte sequences can be
148created. Also, the higher level functions can also much easier operate
149on wide character than on multibyte characters so that a general advise
150is to use wide characters internally whenever text is more than simply
151copied.
152
153The remaining of this chapter will discuss the functions for handling
154wide character strings in parallel with the discussion of the multibyte
155character strings since there is almost always an exact equivalent
156available.
157
b4012b75 158@node String/Array Conventions
28f540f4
RM
159@section String and Array Conventions
160
161This chapter describes both functions that work on arbitrary arrays or
162blocks of memory, and functions that are specific to null-terminated
8a2f1f5b 163arrays of characters and wide characters.
28f540f4
RM
164
165Functions that operate on arbitrary blocks of memory have names
8a2f1f5b
UD
166beginning with @samp{mem} and @samp{wmem} (such as @code{memcpy} and
167@code{wmemcpy}) and invariably take an argument which specifies the size
168(in bytes and wide characters respectively) of the block of memory to
28f540f4 169operate on. The array arguments and return values for these functions
8a2f1f5b
UD
170have type @code{void *} or @code{wchar_t}. As a matter of style, the
171elements of the arrays used with the @samp{mem} functions are referred
172to as ``bytes''. You can pass any kind of pointer to these functions,
173and the @code{sizeof} operator is useful in computing the value for the
174size argument. Parameters to the @samp{wmem} functions must be of type
175@code{wchar_t *}. These functions are not really usable with anything
176but arrays of this type.
177
178In contrast, functions that operate specifically on strings and wide
179character strings have names beginning with @samp{str} and @samp{wcs}
180respectively (such as @code{strcpy} and @code{wcscpy}) and look for a
181null character to terminate the string instead of requiring an explicit
182size argument to be passed. (Some of these functions accept a specified
28f540f4
RM
183maximum length, but they also check for premature termination with a
184null character.) The array arguments and return values for these
8a2f1f5b
UD
185functions have type @code{char *} and @code{wchar_t *} respectively, and
186the array elements are referred to as ``characters'' and ``wide
187characters''.
188
189In many cases, there are both @samp{mem} and @samp{str}/@samp{wcs}
190versions of a function. The one that is more appropriate to use depends
191on the exact situation. When your program is manipulating arbitrary
192arrays or blocks of storage, then you should always use the @samp{mem}
193functions. On the other hand, when you are manipulating null-terminated
194strings it is usually more convenient to use the @samp{str}/@samp{wcs}
195functions, unless you already know the length of the string in advance.
196The @samp{wmem} functions should be used for wide character arrays with
197known size.
198
199@cindex wint_t
200@cindex parameter promotion
201Some of the memory and string functions take single characters as
202arguments. Since a value of type @code{char} is automatically promoted
9dcc8f11 203into a value of type @code{int} when used as a parameter, the functions
8a2f1f5b
UD
204are declared with @code{int} as the type of the parameter in question.
205In case of the wide character function the situation is similarly: the
206parameter type for a single wide character is @code{wint_t} and not
207@code{wchar_t}. This would for many implementations not be necessary
208since the @code{wchar_t} is large enough to not be automatically
209promoted, but since the @w{ISO C} standard does not require such a
210choice of types the @code{wint_t} type is used.
28f540f4 211
b4012b75 212@node String Length
28f540f4
RM
213@section String Length
214
215You can get the length of a string using the @code{strlen} function.
216This function is declared in the header file @file{string.h}.
217@pindex string.h
218
219@comment string.h
f65fd747 220@comment ISO
28f540f4 221@deftypefun size_t strlen (const char *@var{s})
11087373 222@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4 223The @code{strlen} function returns the length of the null-terminated
8a2f1f5b
UD
224string @var{s} in bytes. (In other words, it returns the offset of the
225terminating null character within the array.)
28f540f4
RM
226
227For example,
228@smallexample
229strlen ("hello, world")
230 @result{} 12
231@end smallexample
232
233When applied to a character array, the @code{strlen} function returns
dd7d45e8
UD
234the length of the string stored there, not its allocated size. You can
235get the allocated size of the character array that holds a string using
28f540f4
RM
236the @code{sizeof} operator:
237
238@smallexample
a5113b14 239char string[32] = "hello, world";
28f540f4
RM
240sizeof (string)
241 @result{} 32
242strlen (string)
243 @result{} 12
244@end smallexample
dd7d45e8
UD
245
246But beware, this will not work unless @var{string} is the character
247array itself, not a pointer to it. For example:
248
249@smallexample
250char string[32] = "hello, world";
251char *ptr = string;
252sizeof (string)
253 @result{} 32
254sizeof (ptr)
255 @result{} 4 /* @r{(on a machine with 4 byte pointers)} */
256@end smallexample
257
258This is an easy mistake to make when you are working with functions that
259take string arguments; those arguments are always pointers, not arrays.
260
8a2f1f5b
UD
261It must also be noted that for multibyte encoded strings the return
262value does not have to correspond to the number of characters in the
263string. To get this value the string can be converted to wide
264characters and @code{wcslen} can be used or something like the following
265code can be used:
266
267@smallexample
268/* @r{The input is in @code{string}.}
269 @r{The length is expected in @code{n}.} */
270@{
271 mbstate_t t;
272 char *scopy = string;
273 /* In initial state. */
274 memset (&t, '\0', sizeof (t));
275 /* Determine number of characters. */
276 n = mbsrtowcs (NULL, &scopy, strlen (scopy), &t);
277@}
278@end smallexample
279
280This is cumbersome to do so if the number of characters (as opposed to
281bytes) is needed often it is better to work with wide characters.
282@end deftypefun
283
284The wide character equivalent is declared in @file{wchar.h}.
285
286@comment wchar.h
287@comment ISO
288@deftypefun size_t wcslen (const wchar_t *@var{ws})
11087373 289@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
290The @code{wcslen} function is the wide character equivalent to
291@code{strlen}. The return value is the number of wide characters in the
292wide character string pointed to by @var{ws} (this is also the offset of
293the terminating null wide character of @var{ws}).
294
295Since there are no multi wide character sequences making up one
296character the return value is not only the offset in the array, it is
297also the number of wide characters.
298
299This function was introduced in @w{Amendment 1} to @w{ISO C90}.
28f540f4
RM
300@end deftypefun
301
4547c1a4
UD
302@comment string.h
303@comment GNU
304@deftypefun size_t strnlen (const char *@var{s}, size_t @var{maxlen})
11087373 305@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
306The @code{strnlen} function returns the length of the string @var{s} in
307bytes if this length is smaller than @var{maxlen} bytes. Otherwise it
308returns @var{maxlen}. Therefore this function is equivalent to
ebaf36eb
JM
309@code{(strlen (@var{s}) < @var{maxlen} ? strlen (@var{s}) : @var{maxlen})}
310but it
8a2f1f5b
UD
311is more efficient and works even if the string @var{s} is not
312null-terminated.
4547c1a4
UD
313
314@smallexample
315char string[32] = "hello, world";
316strnlen (string, 32)
317 @result{} 12
318strnlen (string, 5)
319 @result{} 5
320@end smallexample
321
8a2f1f5b
UD
322This function is a GNU extension and is declared in @file{string.h}.
323@end deftypefun
324
325@comment wchar.h
326@comment GNU
327@deftypefun size_t wcsnlen (const wchar_t *@var{ws}, size_t @var{maxlen})
11087373 328@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
329@code{wcsnlen} is the wide character equivalent to @code{strnlen}. The
330@var{maxlen} parameter specifies the maximum number of wide characters.
331
332This function is a GNU extension and is declared in @file{wchar.h}.
4547c1a4
UD
333@end deftypefun
334
b4012b75 335@node Copying and Concatenation
28f540f4
RM
336@section Copying and Concatenation
337
338You can use the functions described in this section to copy the contents
339of strings and arrays, or to append the contents of one string to
8a2f1f5b
UD
340another. The @samp{str} and @samp{mem} functions are declared in the
341header file @file{string.h} while the @samp{wstr} and @samp{wmem}
342functions are declared in the file @file{wchar.h}.
28f540f4 343@pindex string.h
8a2f1f5b 344@pindex wchar.h
28f540f4
RM
345@cindex copying strings and arrays
346@cindex string copy functions
347@cindex array copy functions
348@cindex concatenating strings
349@cindex string concatenation functions
350
351A helpful way to remember the ordering of the arguments to the functions
352in this section is that it corresponds to an assignment expression, with
353the destination array specified to the left of the source array. All
354of these functions return the address of the destination array.
355
356Most of these functions do not work properly if the source and
357destination arrays overlap. For example, if the beginning of the
358destination array overlaps the end of the source array, the original
359contents of that part of the source array may get overwritten before it
360is copied. Even worse, in the case of the string functions, the null
361character marking the end of the string may be lost, and the copy
362function might get stuck in a loop trashing all the memory allocated to
363your program.
364
365All functions that have problems copying between overlapping arrays are
366explicitly identified in this manual. In addition to functions in this
367section, there are a few others like @code{sprintf} (@pxref{Formatted
368Output Functions}) and @code{scanf} (@pxref{Formatted Input
369Functions}).
370
371@comment string.h
f65fd747 372@comment ISO
8a2f1f5b 373@deftypefun {void *} memcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
11087373 374@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
375The @code{memcpy} function copies @var{size} bytes from the object
376beginning at @var{from} into the object beginning at @var{to}. The
377behavior of this function is undefined if the two arrays @var{to} and
378@var{from} overlap; use @code{memmove} instead if overlapping is possible.
379
380The value returned by @code{memcpy} is the value of @var{to}.
381
382Here is an example of how you might use @code{memcpy} to copy the
383contents of an array:
384
385@smallexample
386struct foo *oldarray, *newarray;
387int arraysize;
388@dots{}
389memcpy (new, old, arraysize * sizeof (struct foo));
390@end smallexample
391@end deftypefun
392
8a2f1f5b
UD
393@comment wchar.h
394@comment ISO
79827876 395@deftypefun {wchar_t *} wmemcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
11087373 396@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
397The @code{wmemcpy} function copies @var{size} wide characters from the object
398beginning at @var{wfrom} into the object beginning at @var{wto}. The
399behavior of this function is undefined if the two arrays @var{wto} and
400@var{wfrom} overlap; use @code{wmemmove} instead if overlapping is possible.
401
402The following is a possible implementation of @code{wmemcpy} but there
403are more optimizations possible.
404
405@smallexample
406wchar_t *
407wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
408 size_t size)
409@{
410 return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));
411@}
412@end smallexample
413
414The value returned by @code{wmemcpy} is the value of @var{wto}.
415
416This function was introduced in @w{Amendment 1} to @w{ISO C90}.
417@end deftypefun
418
4547c1a4
UD
419@comment string.h
420@comment GNU
8a2f1f5b 421@deftypefun {void *} mempcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
11087373 422@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
4547c1a4 423The @code{mempcpy} function is nearly identical to the @code{memcpy}
f2ea0f5b 424function. It copies @var{size} bytes from the object beginning at
4547c1a4 425@code{from} into the object pointed to by @var{to}. But instead of
976780fd 426returning the value of @var{to} it returns a pointer to the byte
4547c1a4
UD
427following the last written byte in the object beginning at @var{to}.
428I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
429
430This function is useful in situations where a number of objects shall be
431copied to consecutive memory positions.
432
433@smallexample
434void *
435combine (void *o1, size_t s1, void *o2, size_t s2)
436@{
437 void *result = malloc (s1 + s2);
438 if (result != NULL)
439 mempcpy (mempcpy (result, o1, s1), o2, s2);
440 return result;
441@}
442@end smallexample
443
444This function is a GNU extension.
445@end deftypefun
446
8a2f1f5b
UD
447@comment wchar.h
448@comment GNU
449@deftypefun {wchar_t *} wmempcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
11087373 450@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
451The @code{wmempcpy} function is nearly identical to the @code{wmemcpy}
452function. It copies @var{size} wide characters from the object
453beginning at @code{wfrom} into the object pointed to by @var{wto}. But
454instead of returning the value of @var{wto} it returns a pointer to the
455wide character following the last written wide character in the object
456beginning at @var{wto}. I.e., the value is @code{@var{wto} + @var{size}}.
457
458This function is useful in situations where a number of objects shall be
459copied to consecutive memory positions.
460
461The following is a possible implementation of @code{wmemcpy} but there
462are more optimizations possible.
463
464@smallexample
465wchar_t *
466wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
467 size_t size)
468@{
469 return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
470@}
471@end smallexample
472
473This function is a GNU extension.
474@end deftypefun
475
28f540f4 476@comment string.h
f65fd747 477@comment ISO
28f540f4 478@deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
11087373 479@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
480@code{memmove} copies the @var{size} bytes at @var{from} into the
481@var{size} bytes at @var{to}, even if those two blocks of space
482overlap. In the case of overlap, @code{memmove} is careful to copy the
483original values of the bytes in the block at @var{from}, including those
484bytes which also belong to the block at @var{to}.
8a2f1f5b
UD
485
486The value returned by @code{memmove} is the value of @var{to}.
487@end deftypefun
488
489@comment wchar.h
490@comment ISO
8ded91fb 491@deftypefun {wchar_t *} wmemmove (wchar_t *@var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
11087373 492@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
493@code{wmemmove} copies the @var{size} wide characters at @var{wfrom}
494into the @var{size} wide characters at @var{wto}, even if those two
495blocks of space overlap. In the case of overlap, @code{memmove} is
496careful to copy the original values of the wide characters in the block
497at @var{wfrom}, including those wide characters which also belong to the
498block at @var{wto}.
499
500The following is a possible implementation of @code{wmemcpy} but there
501are more optimizations possible.
502
503@smallexample
504wchar_t *
505wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
506 size_t size)
507@{
508 return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
509@}
510@end smallexample
511
512The value returned by @code{wmemmove} is the value of @var{wto}.
513
514This function is a GNU extension.
28f540f4
RM
515@end deftypefun
516
517@comment string.h
518@comment SVID
8a2f1f5b 519@deftypefun {void *} memccpy (void *restrict @var{to}, const void *restrict @var{from}, int @var{c}, size_t @var{size})
11087373 520@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
521This function copies no more than @var{size} bytes from @var{from} to
522@var{to}, stopping if a byte matching @var{c} is found. The return
523value is a pointer into @var{to} one byte past where @var{c} was copied,
524or a null pointer if no byte matching @var{c} appeared in the first
525@var{size} bytes of @var{from}.
526@end deftypefun
527
528@comment string.h
f65fd747 529@comment ISO
28f540f4 530@deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
11087373 531@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
532This function copies the value of @var{c} (converted to an
533@code{unsigned char}) into each of the first @var{size} bytes of the
534object beginning at @var{block}. It returns the value of @var{block}.
535@end deftypefun
536
8a2f1f5b
UD
537@comment wchar.h
538@comment ISO
539@deftypefun {wchar_t *} wmemset (wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
11087373 540@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
541This function copies the value of @var{wc} into each of the first
542@var{size} wide characters of the object beginning at @var{block}. It
543returns the value of @var{block}.
544@end deftypefun
545
28f540f4 546@comment string.h
f65fd747 547@comment ISO
8a2f1f5b 548@deftypefun {char *} strcpy (char *restrict @var{to}, const char *restrict @var{from})
11087373 549@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
550This copies characters from the string @var{from} (up to and including
551the terminating null character) into the string @var{to}. Like
552@code{memcpy}, this function has undefined results if the strings
553overlap. The return value is the value of @var{to}.
554@end deftypefun
555
8a2f1f5b
UD
556@comment wchar.h
557@comment ISO
558@deftypefun {wchar_t *} wcscpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
11087373 559@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
560This copies wide characters from the string @var{wfrom} (up to and
561including the terminating null wide character) into the string
562@var{wto}. Like @code{wmemcpy}, this function has undefined results if
563the strings overlap. The return value is the value of @var{wto}.
564@end deftypefun
565
28f540f4 566@comment string.h
f65fd747 567@comment ISO
8a2f1f5b 568@deftypefun {char *} strncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
11087373 569@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
570This function is similar to @code{strcpy} but always copies exactly
571@var{size} characters into @var{to}.
572
573If the length of @var{from} is more than @var{size}, then @code{strncpy}
574copies just the first @var{size} characters. Note that in this case
575there is no null terminator written into @var{to}.
576
577If the length of @var{from} is less than @var{size}, then @code{strncpy}
578copies all of @var{from}, followed by enough null characters to add up
579to @var{size} characters in all. This behavior is rarely useful, but it
f65fd747 580is specified by the @w{ISO C} standard.
28f540f4
RM
581
582The behavior of @code{strncpy} is undefined if the strings overlap.
583
584Using @code{strncpy} as opposed to @code{strcpy} is a way to avoid bugs
585relating to writing past the end of the allocated space for @var{to}.
586However, it can also make your program much slower in one common case:
587copying a string which is probably small into a potentially large buffer.
588In this case, @var{size} may be large, and when it is, @code{strncpy} will
589waste a considerable amount of time copying null characters.
590@end deftypefun
591
8a2f1f5b
UD
592@comment wchar.h
593@comment ISO
594@deftypefun {wchar_t *} wcsncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
11087373 595@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
596This function is similar to @code{wcscpy} but always copies exactly
597@var{size} wide characters into @var{wto}.
598
599If the length of @var{wfrom} is more than @var{size}, then
600@code{wcsncpy} copies just the first @var{size} wide characters. Note
601that in this case there is no null terminator written into @var{wto}.
602
603If the length of @var{wfrom} is less than @var{size}, then
604@code{wcsncpy} copies all of @var{wfrom}, followed by enough null wide
605characters to add up to @var{size} wide characters in all. This
606behavior is rarely useful, but it is specified by the @w{ISO C}
607standard.
608
609The behavior of @code{wcsncpy} is undefined if the strings overlap.
610
611Using @code{wcsncpy} as opposed to @code{wcscpy} is a way to avoid bugs
612relating to writing past the end of the allocated space for @var{wto}.
613However, it can also make your program much slower in one common case:
614copying a string which is probably small into a potentially large buffer.
615In this case, @var{size} may be large, and when it is, @code{wcsncpy} will
616waste a considerable amount of time copying null wide characters.
617@end deftypefun
618
28f540f4
RM
619@comment string.h
620@comment SVID
621@deftypefun {char *} strdup (const char *@var{s})
11087373 622@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
623This function copies the null-terminated string @var{s} into a newly
624allocated string. The string is allocated using @code{malloc}; see
625@ref{Unconstrained Allocation}. If @code{malloc} cannot allocate space
626for the new string, @code{strdup} returns a null pointer. Otherwise it
627returns a pointer to the new string.
628@end deftypefun
629
8a2f1f5b
UD
630@comment wchar.h
631@comment GNU
632@deftypefun {wchar_t *} wcsdup (const wchar_t *@var{ws})
11087373 633@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
8a2f1f5b
UD
634This function copies the null-terminated wide character string @var{ws}
635into a newly allocated string. The string is allocated using
636@code{malloc}; see @ref{Unconstrained Allocation}. If @code{malloc}
637cannot allocate space for the new string, @code{wcsdup} returns a null
638pointer. Otherwise it returns a pointer to the new wide character
639string.
640
641This function is a GNU extension.
642@end deftypefun
643
706074a5
UD
644@comment string.h
645@comment GNU
646@deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
11087373 647@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
706074a5
UD
648This function is similar to @code{strdup} but always copies at most
649@var{size} characters into the newly allocated string.
650
651If the length of @var{s} is more than @var{size}, then @code{strndup}
652copies just the first @var{size} characters and adds a closing null
653terminator. Otherwise all characters are copied and the string is
654terminated.
655
656This function is different to @code{strncpy} in that it always
657terminates the destination string.
738d1a5a
UD
658
659@code{strndup} is a GNU extension.
706074a5
UD
660@end deftypefun
661
28f540f4
RM
662@comment string.h
663@comment Unknown origin
8a2f1f5b 664@deftypefun {char *} stpcpy (char *restrict @var{to}, const char *restrict @var{from})
11087373 665@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
666This function is like @code{strcpy}, except that it returns a pointer to
667the end of the string @var{to} (that is, the address of the terminating
8a2f1f5b 668null character @code{to + strlen (from)}) rather than the beginning.
28f540f4
RM
669
670For example, this program uses @code{stpcpy} to concatenate @samp{foo}
671and @samp{bar} to produce @samp{foobar}, which it then prints.
672
673@smallexample
674@include stpcpy.c.texi
675@end smallexample
676
f65fd747 677This function is not part of the ISO or POSIX standards, and is not
28f540f4
RM
678customary on Unix systems, but we did not invent it either. Perhaps it
679comes from MS-DOG.
680
8a2f1f5b
UD
681Its behavior is undefined if the strings overlap. The function is
682declared in @file{string.h}.
683@end deftypefun
684
685@comment wchar.h
686@comment GNU
687@deftypefun {wchar_t *} wcpcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
11087373 688@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
689This function is like @code{wcscpy}, except that it returns a pointer to
690the end of the string @var{wto} (that is, the address of the terminating
691null character @code{wto + strlen (wfrom)}) rather than the beginning.
692
693This function is not part of ISO or POSIX but was found useful while
1f77f049 694developing @theglibc{} itself.
8a2f1f5b
UD
695
696The behavior of @code{wcpcpy} is undefined if the strings overlap.
697
698@code{wcpcpy} is a GNU extension and is declared in @file{wchar.h}.
28f540f4
RM
699@end deftypefun
700
706074a5
UD
701@comment string.h
702@comment GNU
8a2f1f5b 703@deftypefun {char *} stpncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
11087373 704@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
706074a5
UD
705This function is similar to @code{stpcpy} but copies always exactly
706@var{size} characters into @var{to}.
707
f24a6d08 708If the length of @var{from} is more than @var{size}, then @code{stpncpy}
706074a5
UD
709copies just the first @var{size} characters and returns a pointer to the
710character directly following the one which was copied last. Note that in
711this case there is no null terminator written into @var{to}.
712
713If the length of @var{from} is less than @var{size}, then @code{stpncpy}
714copies all of @var{from}, followed by enough null characters to add up
0bc93a2f
AJ
715to @var{size} characters in all. This behavior is rarely useful, but it
716is implemented to be useful in contexts where this behavior of the
706074a5
UD
717@code{strncpy} is used. @code{stpncpy} returns a pointer to the
718@emph{first} written null character.
719
f65fd747 720This function is not part of ISO or POSIX but was found useful while
1f77f049 721developing @theglibc{} itself.
706074a5 722
0bc93a2f 723Its behavior is undefined if the strings overlap. The function is
8a2f1f5b
UD
724declared in @file{string.h}.
725@end deftypefun
726
727@comment wchar.h
728@comment GNU
729@deftypefun {wchar_t *} wcpncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
11087373 730@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
731This function is similar to @code{wcpcpy} but copies always exactly
732@var{wsize} characters into @var{wto}.
733
f24a6d08 734If the length of @var{wfrom} is more than @var{size}, then
8a2f1f5b 735@code{wcpncpy} copies just the first @var{size} wide characters and
80b54217
UD
736returns a pointer to the wide character directly following the last
737non-null wide character which was copied last. Note that in this case
738there is no null terminator written into @var{wto}.
8a2f1f5b
UD
739
740If the length of @var{wfrom} is less than @var{size}, then @code{wcpncpy}
741copies all of @var{wfrom}, followed by enough null characters to add up
0bc93a2f
AJ
742to @var{size} characters in all. This behavior is rarely useful, but it
743is implemented to be useful in contexts where this behavior of the
8a2f1f5b
UD
744@code{wcsncpy} is used. @code{wcpncpy} returns a pointer to the
745@emph{first} written null character.
746
747This function is not part of ISO or POSIX but was found useful while
1f77f049 748developing @theglibc{} itself.
8a2f1f5b 749
0bc93a2f 750Its behavior is undefined if the strings overlap.
8a2f1f5b
UD
751
752@code{wcpncpy} is a GNU extension and is declared in @file{wchar.h}.
706074a5
UD
753@end deftypefun
754
755@comment string.h
756@comment GNU
26b4d766 757@deftypefn {Macro} {char *} strdupa (const char *@var{s})
11087373 758@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
976780fd 759This macro is similar to @code{strdup} but allocates the new string
dd7d45e8
UD
760using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
761Automatic}). This means of course the returned string has the same
762limitations as any block of memory allocated using @code{alloca}.
706074a5 763
dd7d45e8 764For obvious reasons @code{strdupa} is implemented only as a macro;
40a55d20 765you cannot get the address of this function. Despite this limitation
706074a5
UD
766it is a useful function. The following code shows a situation where
767using @code{malloc} would be a lot more expensive.
768
769@smallexample
770@include strdupa.c.texi
771@end smallexample
772
773Please note that calling @code{strtok} using @var{path} directly is
8a2f1f5b
UD
774invalid. It is also not allowed to call @code{strdupa} in the argument
775list of @code{strtok} since @code{strdupa} uses @code{alloca}
776(@pxref{Variable Size Automatic}) can interfere with the parameter
777passing.
706074a5
UD
778
779This function is only available if GNU CC is used.
26b4d766 780@end deftypefn
706074a5
UD
781
782@comment string.h
783@comment GNU
26b4d766 784@deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
11087373 785@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
706074a5
UD
786This function is similar to @code{strndup} but like @code{strdupa} it
787allocates the new string using @code{alloca}
788@pxref{Variable Size Automatic}. The same advantages and limitations
789of @code{strdupa} are valid for @code{strndupa}, too.
790
dd7d45e8 791This function is implemented only as a macro, just like @code{strdupa}.
8a2f1f5b
UD
792Just as @code{strdupa} this macro also must not be used inside the
793parameter list in a function call.
706074a5
UD
794
795@code{strndupa} is only available if GNU CC is used.
26b4d766 796@end deftypefn
706074a5 797
28f540f4 798@comment string.h
f65fd747 799@comment ISO
8a2f1f5b 800@deftypefun {char *} strcat (char *restrict @var{to}, const char *restrict @var{from})
11087373 801@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
802The @code{strcat} function is similar to @code{strcpy}, except that the
803characters from @var{from} are concatenated or appended to the end of
804@var{to}, instead of overwriting it. That is, the first character from
805@var{from} overwrites the null character marking the end of @var{to}.
806
807An equivalent definition for @code{strcat} would be:
808
809@smallexample
810char *
8a2f1f5b 811strcat (char *restrict to, const char *restrict from)
28f540f4
RM
812@{
813 strcpy (to + strlen (to), from);
814 return to;
815@}
816@end smallexample
817
818This function has undefined results if the strings overlap.
819@end deftypefun
820
8a2f1f5b
UD
821@comment wchar.h
822@comment ISO
823@deftypefun {wchar_t *} wcscat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
11087373 824@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
825The @code{wcscat} function is similar to @code{wcscpy}, except that the
826characters from @var{wfrom} are concatenated or appended to the end of
827@var{wto}, instead of overwriting it. That is, the first character from
828@var{wfrom} overwrites the null character marking the end of @var{wto}.
829
830An equivalent definition for @code{wcscat} would be:
831
832@smallexample
833wchar_t *
834wcscat (wchar_t *wto, const wchar_t *wfrom)
835@{
836 wcscpy (wto + wcslen (wto), wfrom);
837 return wto;
838@}
839@end smallexample
840
841This function has undefined results if the strings overlap.
842@end deftypefun
843
844Programmers using the @code{strcat} or @code{wcscat} function (or the
845following @code{strncat} or @code{wcsncar} functions for that matter)
846can easily be recognized as lazy and reckless. In almost all situations
847the lengths of the participating strings are known (it better should be
848since how can one otherwise ensure the allocated size of the buffer is
849sufficient?) Or at least, one could know them if one keeps track of the
ee2752ea 850results of the various function calls. But then it is very inefficient
8a2f1f5b
UD
851to use @code{strcat}/@code{wcscat}. A lot of time is wasted finding the
852end of the destination string so that the actual copying can start.
853This is a common example:
ee2752ea 854
ee2752ea
UD
855@cindex va_copy
856@smallexample
49c091e5 857/* @r{This function concatenates arbitrarily many strings. The last}
ee2752ea
UD
858 @r{parameter must be @code{NULL}.} */
859char *
8a2f1f5b 860concat (const char *str, @dots{})
ee2752ea
UD
861@{
862 va_list ap, ap2;
863 size_t total = 1;
864 const char *s;
865 char *result;
866
867 va_start (ap, str);
b5982523 868 va_copy (ap2, ap);
ee2752ea
UD
869
870 /* @r{Determine how much space we need.} */
871 for (s = str; s != NULL; s = va_arg (ap, const char *))
872 total += strlen (s);
873
874 va_end (ap);
875
876 result = (char *) malloc (total);
877 if (result != NULL)
878 @{
879 result[0] = '\0';
880
881 /* @r{Copy the strings.} */
882 for (s = str; s != NULL; s = va_arg (ap2, const char *))
883 strcat (result, s);
884 @}
885
886 va_end (ap2);
887
888 return result;
889@}
890@end smallexample
891
892This looks quite simple, especially the second loop where the strings
893are actually copied. But these innocent lines hide a major performance
894penalty. Just imagine that ten strings of 100 bytes each have to be
895concatenated. For the second string we search the already stored 100
896bytes for the end of the string so that we can append the next string.
897For all strings in total the comparisons necessary to find the end of
898the intermediate results sums up to 5500! If we combine the copying
899with the search for the allocation we can write this function more
49c091e5 900efficient:
ee2752ea
UD
901
902@smallexample
903char *
8a2f1f5b 904concat (const char *str, @dots{})
ee2752ea
UD
905@{
906 va_list ap;
907 size_t allocated = 100;
908 char *result = (char *) malloc (allocated);
ee2752ea 909
623281e0 910 if (result != NULL)
ee2752ea
UD
911 @{
912 char *newp;
623281e0 913 char *wp;
1bfb7291 914 const char *s;
ee2752ea 915
623281e0 916 va_start (ap, str);
ee2752ea
UD
917
918 wp = result;
919 for (s = str; s != NULL; s = va_arg (ap, const char *))
920 @{
921 size_t len = strlen (s);
922
923 /* @r{Resize the allocated memory if necessary.} */
924 if (wp + len + 1 > result + allocated)
925 @{
926 allocated = (allocated + len) * 2;
927 newp = (char *) realloc (result, allocated);
928 if (newp == NULL)
929 @{
930 free (result);
931 return NULL;
932 @}
933 wp = newp + (wp - result);
934 result = newp;
935 @}
936
937 wp = mempcpy (wp, s, len);
938 @}
939
940 /* @r{Terminate the result string.} */
941 *wp++ = '\0';
942
943 /* @r{Resize memory to the optimal size.} */
944 newp = realloc (result, wp - result);
945 if (newp != NULL)
946 result = newp;
947
948 va_end (ap);
949 @}
950
951 return result;
952@}
953@end smallexample
954
955With a bit more knowledge about the input strings one could fine-tune
956the memory allocation. The difference we are pointing to here is that
957we don't use @code{strcat} anymore. We always keep track of the length
958of the current intermediate result so we can safe us the search for the
959end of the string and use @code{mempcpy}. Please note that we also
960don't use @code{stpcpy} which might seem more natural since we handle
961with strings. But this is not necessary since we already know the
962length of the string and therefore can use the faster memory copying
8a2f1f5b 963function. The example would work for wide characters the same way.
ee2752ea
UD
964
965Whenever a programmer feels the need to use @code{strcat} she or he
966should think twice and look through the program whether the code cannot
967be rewritten to take advantage of already calculated results. Again: it
968is almost always unnecessary to use @code{strcat}.
969
28f540f4 970@comment string.h
f65fd747 971@comment ISO
8a2f1f5b 972@deftypefun {char *} strncat (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
11087373 973@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
974This function is like @code{strcat} except that not more than @var{size}
975characters from @var{from} are appended to the end of @var{to}. A
976single null character is also always appended to @var{to}, so the total
977allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
978longer than its initial length.
979
980The @code{strncat} function could be implemented like this:
981
982@smallexample
983@group
984char *
985strncat (char *to, const char *from, size_t size)
986@{
b1fe1f2b
OB
987 memcpy (to + strlen (to), from, strnlen (from, size));
988 to[strlen (to) + strnlen (from, size)] = '\0';
28f540f4
RM
989 return to;
990@}
991@end group
992@end smallexample
993
994The behavior of @code{strncat} is undefined if the strings overlap.
995@end deftypefun
996
8a2f1f5b
UD
997@comment wchar.h
998@comment ISO
999@deftypefun {wchar_t *} wcsncat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
11087373 1000@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1001This function is like @code{wcscat} except that not more than @var{size}
1002characters from @var{from} are appended to the end of @var{to}. A
1003single null character is also always appended to @var{to}, so the total
1004allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
1005longer than its initial length.
1006
1007The @code{wcsncat} function could be implemented like this:
1008
1009@smallexample
1010@group
1011wchar_t *
1012wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom,
1013 size_t size)
1014@{
b1fe1f2b
OB
1015 memcpy (wto + wcslen (wto), wfrom, wcsnlen (wfrom, size) * sizeof (wchar_t));
1016 wto[wcslen (to) + wcsnlen (wfrom, size)] = '\0';
8a2f1f5b
UD
1017 return wto;
1018@}
1019@end group
1020@end smallexample
1021
1022The behavior of @code{wcsncat} is undefined if the strings overlap.
1023@end deftypefun
1024
1025Here is an example showing the use of @code{strncpy} and @code{strncat}
1026(the wide character version is equivalent). Notice how, in the call to
1027@code{strncat}, the @var{size} parameter is computed to avoid
1028overflowing the character array @code{buffer}.
28f540f4
RM
1029
1030@smallexample
1031@include strncat.c.texi
1032@end smallexample
1033
1034@noindent
1035The output produced by this program looks like:
1036
1037@smallexample
1038hello
1039hello, wo
1040@end smallexample
1041
1042@comment string.h
1043@comment BSD
af6f3906 1044@deftypefun void bcopy (const void *@var{from}, void *@var{to}, size_t @var{size})
11087373 1045@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1046This is a partially obsolete alternative for @code{memmove}, derived from
1047BSD. Note that it is not quite equivalent to @code{memmove}, because the
af6f3906 1048arguments are not in the same order and there is no return value.
28f540f4
RM
1049@end deftypefun
1050
1051@comment string.h
1052@comment BSD
af6f3906 1053@deftypefun void bzero (void *@var{block}, size_t @var{size})
11087373 1054@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1055This is a partially obsolete alternative for @code{memset}, derived from
1056BSD. Note that it is not as general as @code{memset}, because the only
1057value it can store is zero.
1058@end deftypefun
1059
b4012b75 1060@node String/Array Comparison
28f540f4
RM
1061@section String/Array Comparison
1062@cindex comparing strings and arrays
1063@cindex string comparison functions
1064@cindex array comparison functions
1065@cindex predicates on strings
1066@cindex predicates on arrays
1067
1068You can use the functions in this section to perform comparisons on the
1069contents of strings and arrays. As well as checking for equality, these
1070functions can also be used as the ordering functions for sorting
1071operations. @xref{Searching and Sorting}, for an example of this.
1072
1073Unlike most comparison operations in C, the string comparison functions
1074return a nonzero value if the strings are @emph{not} equivalent rather
1075than if they are. The sign of the value indicates the relative ordering
1076of the first characters in the strings that are not equivalent: a
1077negative value indicates that the first string is ``less'' than the
a5113b14 1078second, while a positive value indicates that the first string is
28f540f4
RM
1079``greater''.
1080
1081The most common use of these functions is to check only for equality.
1082This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
1083
1084All of these functions are declared in the header file @file{string.h}.
1085@pindex string.h
1086
1087@comment string.h
f65fd747 1088@comment ISO
28f540f4 1089@deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
11087373 1090@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1091The function @code{memcmp} compares the @var{size} bytes of memory
1092beginning at @var{a1} against the @var{size} bytes of memory beginning
1093at @var{a2}. The value returned has the same sign as the difference
1094between the first differing pair of bytes (interpreted as @code{unsigned
1095char} objects, then promoted to @code{int}).
1096
1097If the contents of the two blocks are equal, @code{memcmp} returns
1098@code{0}.
1099@end deftypefun
1100
8ded91fb 1101@comment wchar.h
8a2f1f5b
UD
1102@comment ISO
1103@deftypefun int wmemcmp (const wchar_t *@var{a1}, const wchar_t *@var{a2}, size_t @var{size})
11087373 1104@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1105The function @code{wmemcmp} compares the @var{size} wide characters
1106beginning at @var{a1} against the @var{size} wide characters beginning
1107at @var{a2}. The value returned is smaller than or larger than zero
1108depending on whether the first differing wide character is @var{a1} is
1109smaller or larger than the corresponding character in @var{a2}.
1110
1111If the contents of the two blocks are equal, @code{wmemcmp} returns
1112@code{0}.
1113@end deftypefun
1114
28f540f4
RM
1115On arbitrary arrays, the @code{memcmp} function is mostly useful for
1116testing equality. It usually isn't meaningful to do byte-wise ordering
1117comparisons on arrays of things other than bytes. For example, a
1118byte-wise comparison on the bytes that make up floating-point numbers
1119isn't likely to tell you anything about the relationship between the
1120values of the floating-point numbers.
1121
8a2f1f5b
UD
1122@code{wmemcmp} is really only useful to compare arrays of type
1123@code{wchar_t} since the function looks at @code{sizeof (wchar_t)} bytes
1124at a time and this number of bytes is system dependent.
1125
28f540f4
RM
1126You should also be careful about using @code{memcmp} to compare objects
1127that can contain ``holes'', such as the padding inserted into structure
1128objects to enforce alignment requirements, extra space at the end of
1129unions, and extra characters at the ends of strings whose length is less
1130than their allocated size. The contents of these ``holes'' are
1131indeterminate and may cause strange behavior when performing byte-wise
1132comparisons. For more predictable results, perform an explicit
1133component-wise comparison.
1134
1135For example, given a structure type definition like:
1136
1137@smallexample
1138struct foo
1139 @{
1140 unsigned char tag;
1141 union
1142 @{
1143 double f;
1144 long i;
1145 char *p;
1146 @} value;
1147 @};
1148@end smallexample
1149
1150@noindent
1151you are better off writing a specialized comparison function to compare
1152@code{struct foo} objects instead of comparing them with @code{memcmp}.
1153
1154@comment string.h
f65fd747 1155@comment ISO
28f540f4 1156@deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
11087373 1157@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1158The @code{strcmp} function compares the string @var{s1} against
1159@var{s2}, returning a value that has the same sign as the difference
1160between the first differing pair of characters (interpreted as
1161@code{unsigned char} objects, then promoted to @code{int}).
1162
1163If the two strings are equal, @code{strcmp} returns @code{0}.
1164
1165A consequence of the ordering used by @code{strcmp} is that if @var{s1}
1166is an initial substring of @var{s2}, then @var{s1} is considered to be
1167``less than'' @var{s2}.
8a2f1f5b
UD
1168
1169@code{strcmp} does not take sorting conventions of the language the
1170strings are written in into account. To get that one has to use
1171@code{strcoll}.
1172@end deftypefun
1173
1174@comment wchar.h
1175@comment ISO
1176@deftypefun int wcscmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
11087373 1177@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1178
1179The @code{wcscmp} function compares the wide character string @var{ws1}
1180against @var{ws2}. The value returned is smaller than or larger than zero
1181depending on whether the first differing wide character is @var{ws1} is
1182smaller or larger than the corresponding character in @var{ws2}.
1183
1184If the two strings are equal, @code{wcscmp} returns @code{0}.
1185
1186A consequence of the ordering used by @code{wcscmp} is that if @var{ws1}
1187is an initial substring of @var{ws2}, then @var{ws1} is considered to be
1188``less than'' @var{ws2}.
1189
1190@code{wcscmp} does not take sorting conventions of the language the
1191strings are written in into account. To get that one has to use
1192@code{wcscoll}.
28f540f4
RM
1193@end deftypefun
1194
1195@comment string.h
1196@comment BSD
1197@deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
11087373
AO
1198@safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1199@c Although this calls tolower multiple times, it's a macro, and
1200@c strcasecmp is optimized so that the locale pointer is read only once.
1201@c There are some asm implementations too, for which the single-read
1202@c from locale TLS pointers also applies.
4547c1a4 1203This function is like @code{strcmp}, except that differences in case are
dd7d45e8 1204ignored. How uppercase and lowercase characters are related is
4547c1a4
UD
1205determined by the currently selected locale. In the standard @code{"C"}
1206locale the characters @"A and @"a do not match but in a locale which
dd7d45e8 1207regards these characters as parts of the alphabet they do match.
28f540f4 1208
85c165be 1209@noindent
28f540f4
RM
1210@code{strcasecmp} is derived from BSD.
1211@end deftypefun
1212
8a2f1f5b
UD
1213@comment wchar.h
1214@comment GNU
8ded91fb 1215@deftypefun int wcscasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
11087373
AO
1216@safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1217@c Since towlower is not a macro, the locale object may be read multiple
1218@c times.
8a2f1f5b
UD
1219This function is like @code{wcscmp}, except that differences in case are
1220ignored. How uppercase and lowercase characters are related is
1221determined by the currently selected locale. In the standard @code{"C"}
1222locale the characters @"A and @"a do not match but in a locale which
1223regards these characters as parts of the alphabet they do match.
1224
1225@noindent
1226@code{wcscasecmp} is a GNU extension.
1227@end deftypefun
1228
1229@comment string.h
1230@comment ISO
1231@deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
11087373 1232@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b 1233This function is the similar to @code{strcmp}, except that no more than
11bf311e
UD
1234@var{size} characters are compared. In other words, if the two
1235strings are the same in their first @var{size} characters, the
8a2f1f5b
UD
1236return value is zero.
1237@end deftypefun
1238
1239@comment wchar.h
1240@comment ISO
1241@deftypefun int wcsncmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2}, size_t @var{size})
11087373 1242@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1243This function is the similar to @code{wcscmp}, except that no more than
1244@var{size} wide characters are compared. In other words, if the two
1245strings are the same in their first @var{size} wide characters, the
1246return value is zero.
1247@end deftypefun
1248
28f540f4
RM
1249@comment string.h
1250@comment BSD
1251@deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
11087373 1252@safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
28f540f4 1253This function is like @code{strncmp}, except that differences in case
dd7d45e8
UD
1254are ignored. Like @code{strcasecmp}, it is locale dependent how
1255uppercase and lowercase characters are related.
28f540f4 1256
85c165be 1257@noindent
28f540f4
RM
1258@code{strncasecmp} is a GNU extension.
1259@end deftypefun
1260
8a2f1f5b
UD
1261@comment wchar.h
1262@comment GNU
1263@deftypefun int wcsncasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{s2}, size_t @var{n})
11087373 1264@safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
8a2f1f5b
UD
1265This function is like @code{wcsncmp}, except that differences in case
1266are ignored. Like @code{wcscasecmp}, it is locale dependent how
1267uppercase and lowercase characters are related.
1268
1269@noindent
1270@code{wcsncasecmp} is a GNU extension.
28f540f4
RM
1271@end deftypefun
1272
8a2f1f5b
UD
1273Here are some examples showing the use of @code{strcmp} and
1274@code{strncmp} (equivalent examples can be constructed for the wide
1275character functions). These examples assume the use of the ASCII
1276character set. (If some other character set---say, EBCDIC---is used
1277instead, then the glyphs are associated with different numeric codes,
1278and the return values and ordering may differ.)
28f540f4
RM
1279
1280@smallexample
1281strcmp ("hello", "hello")
1282 @result{} 0 /* @r{These two strings are the same.} */
1283strcmp ("hello", "Hello")
1284 @result{} 32 /* @r{Comparisons are case-sensitive.} */
1285strcmp ("hello", "world")
1286 @result{} -15 /* @r{The character @code{'h'} comes before @code{'w'}.} */
1287strcmp ("hello", "hello, world")
1288 @result{} -44 /* @r{Comparing a null character against a comma.} */
6952e59e 1289strncmp ("hello", "hello, world", 5)
28f540f4
RM
1290 @result{} 0 /* @r{The initial 5 characters are the same.} */
1291strncmp ("hello, world", "hello, stupid world!!!", 5)
1292 @result{} 0 /* @r{The initial 5 characters are the same.} */
1293@end smallexample
1294
1f205a47
UD
1295@comment string.h
1296@comment GNU
1297@deftypefun int strverscmp (const char *@var{s1}, const char *@var{s2})
11087373
AO
1298@safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1299@c Calls isdigit multiple times, locale may change in between.
1f205a47 1300The @code{strverscmp} function compares the string @var{s1} against
f2282d42
RM
1301@var{s2}, considering them as holding indices/version numbers. The
1302return value follows the same conventions as found in the
1303@code{strcmp} function. In fact, if @var{s1} and @var{s2} contain no
1304digits, @code{strverscmp} behaves like @code{strcmp}.
1f205a47 1305
f2ea0f5b 1306Basically, we compare strings normally (character by character), until
1f205a47 1307we find a digit in each string - then we enter a special comparison
dd7d45e8 1308mode, where each sequence of digits is taken as a whole. If we reach the
1f205a47
UD
1309end of these two parts without noticing a difference, we return to the
1310standard comparison mode. There are two types of numeric parts:
f2ea0f5b 1311"integral" and "fractional" (those begin with a '0'). The types
1f205a47
UD
1312of the numeric parts affect the way we sort them:
1313
1314@itemize @bullet
1315@item
1316integral/integral: we compare values as you would expect.
1317
1318@item
f2ea0f5b 1319fractional/integral: the fractional part is less than the integral one.
1f205a47
UD
1320Again, no surprise.
1321
1322@item
f2ea0f5b
UD
1323fractional/fractional: the things become a bit more complex.
1324If the common prefix contains only leading zeroes, the longest part is less
1325than the other one; else the comparison behaves normally.
1f205a47
UD
1326@end itemize
1327
1328@smallexample
1329strverscmp ("no digit", "no digit")
0bc93a2f 1330 @result{} 0 /* @r{same behavior as strcmp.} */
1f205a47
UD
1331strverscmp ("item#99", "item#100")
1332 @result{} <0 /* @r{same prefix, but 99 < 100.} */
1333strverscmp ("alpha1", "alpha001")
f2ea0f5b 1334 @result{} >0 /* @r{fractional part inferior to integral one.} */
1f205a47 1335strverscmp ("part1_f012", "part1_f01")
f2ea0f5b 1336 @result{} >0 /* @r{two fractional parts.} */
1f205a47
UD
1337strverscmp ("foo.009", "foo.0")
1338 @result{} <0 /* @r{idem, but with leading zeroes only.} */
1339@end smallexample
1340
f2ea0f5b 1341This function is especially useful when dealing with filename sorting,
1f205a47
UD
1342because filenames frequently hold indices/version numbers.
1343
1344@code{strverscmp} is a GNU extension.
1345@end deftypefun
1346
28f540f4
RM
1347@comment string.h
1348@comment BSD
1349@deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
11087373 1350@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1351This is an obsolete alias for @code{memcmp}, derived from BSD.
1352@end deftypefun
1353
b4012b75 1354@node Collation Functions
28f540f4
RM
1355@section Collation Functions
1356
1357@cindex collating strings
1358@cindex string collation functions
1359
1360In some locales, the conventions for lexicographic ordering differ from
1361the strict numeric ordering of character codes. For example, in Spanish
1362most glyphs with diacritical marks such as accents are not considered
1363distinct letters for the purposes of collation. On the other hand, the
1364two-character sequence @samp{ll} is treated as a single letter that is
1365collated immediately after @samp{l}.
1366
1367You can use the functions @code{strcoll} and @code{strxfrm} (declared in
8a2f1f5b
UD
1368the headers file @file{string.h}) and @code{wcscoll} and @code{wcsxfrm}
1369(declared in the headers file @file{wchar}) to compare strings using a
1370collation ordering appropriate for the current locale. The locale used
1371by these functions in particular can be specified by setting the locale
1372for the @code{LC_COLLATE} category; see @ref{Locales}.
28f540f4 1373@pindex string.h
8a2f1f5b 1374@pindex wchar.h
28f540f4
RM
1375
1376In the standard C locale, the collation sequence for @code{strcoll} is
8a2f1f5b
UD
1377the same as that for @code{strcmp}. Similarly, @code{wcscoll} and
1378@code{wcscmp} are the same in this situation.
28f540f4
RM
1379
1380Effectively, the way these functions work is by applying a mapping to
1381transform the characters in a string to a byte sequence that represents
1382the string's position in the collating sequence of the current locale.
1383Comparing two such byte sequences in a simple fashion is equivalent to
1384comparing the strings with the locale's collating sequence.
1385
8a2f1f5b
UD
1386The functions @code{strcoll} and @code{wcscoll} perform this translation
1387implicitly, in order to do one comparison. By contrast, @code{strxfrm}
1388and @code{wcsxfrm} perform the mapping explicitly. If you are making
1389multiple comparisons using the same string or set of strings, it is
1390likely to be more efficient to use @code{strxfrm} or @code{wcsxfrm} to
1391transform all the strings just once, and subsequently compare the
1392transformed strings with @code{strcmp} or @code{wcscmp}.
28f540f4
RM
1393
1394@comment string.h
f65fd747 1395@comment ISO
28f540f4 1396@deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
11087373
AO
1397@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1398@c Calls strcoll_l with the current locale, which dereferences only the
1399@c LC_COLLATE data pointer.
28f540f4
RM
1400The @code{strcoll} function is similar to @code{strcmp} but uses the
1401collating sequence of the current locale for collation (the
1402@code{LC_COLLATE} locale).
1403@end deftypefun
1404
8a2f1f5b
UD
1405@comment wchar.h
1406@comment ISO
1407@deftypefun int wcscoll (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
11087373
AO
1408@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1409@c Same as strcoll, but calling wcscoll_l.
8a2f1f5b
UD
1410The @code{wcscoll} function is similar to @code{wcscmp} but uses the
1411collating sequence of the current locale for collation (the
1412@code{LC_COLLATE} locale).
1413@end deftypefun
1414
28f540f4
RM
1415Here is an example of sorting an array of strings, using @code{strcoll}
1416to compare them. The actual sort algorithm is not written here; it
1417comes from @code{qsort} (@pxref{Array Sort Function}). The job of the
1418code shown here is to say how to compare the strings while sorting them.
1419(Later on in this section, we will show a way to do this more
1420efficiently using @code{strxfrm}.)
1421
1422@smallexample
1423/* @r{This is the comparison function used with @code{qsort}.} */
1424
1425int
e39745ff 1426compare_elements (const void *v1, const void *v2)
28f540f4 1427@{
e39745ff 1428 char * const *p1 = v1;
a9f5ce09 1429 char * const *p2 = v2;
e39745ff 1430
28f540f4
RM
1431 return strcoll (*p1, *p2);
1432@}
1433
1434/* @r{This is the entry point---the function to sort}
1435 @r{strings using the locale's collating sequence.} */
1436
1437void
1438sort_strings (char **array, int nstrings)
1439@{
1440 /* @r{Sort @code{temp_array} by comparing the strings.} */
9fc19e48
UD
1441 qsort (array, nstrings,
1442 sizeof (char *), compare_elements);
28f540f4
RM
1443@}
1444@end smallexample
1445
1446@cindex converting string to collation order
1447@comment string.h
f65fd747 1448@comment ISO
8a2f1f5b 1449@deftypefun size_t strxfrm (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
11087373 1450@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
8a2f1f5b
UD
1451The function @code{strxfrm} transforms the string @var{from} using the
1452collation transformation determined by the locale currently selected for
28f540f4
RM
1453collation, and stores the transformed string in the array @var{to}. Up
1454to @var{size} characters (including a terminating null character) are
1455stored.
1456
1457The behavior is undefined if the strings @var{to} and @var{from}
1458overlap; see @ref{Copying and Concatenation}.
1459
1460The return value is the length of the entire transformed string. This
1461value is not affected by the value of @var{size}, but if it is greater
a5113b14
UD
1462or equal than @var{size}, it means that the transformed string did not
1463entirely fit in the array @var{to}. In this case, only as much of the
1464string as actually fits was stored. To get the whole transformed
1465string, call @code{strxfrm} again with a bigger output array.
28f540f4
RM
1466
1467The transformed string may be longer than the original string, and it
1468may also be shorter.
1469
1470If @var{size} is zero, no characters are stored in @var{to}. In this
1471case, @code{strxfrm} simply returns the number of characters that would
1472be the length of the transformed string. This is useful for determining
8a2f1f5b
UD
1473what size the allocated array should be. It does not matter what
1474@var{to} is if @var{size} is zero; @var{to} may even be a null pointer.
1475@end deftypefun
1476
1477@comment wchar.h
1478@comment ISO
1479@deftypefun size_t wcsxfrm (wchar_t *restrict @var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
11087373 1480@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
8a2f1f5b
UD
1481The function @code{wcsxfrm} transforms wide character string @var{wfrom}
1482using the collation transformation determined by the locale currently
1483selected for collation, and stores the transformed string in the array
1484@var{wto}. Up to @var{size} wide characters (including a terminating null
1485character) are stored.
1486
1487The behavior is undefined if the strings @var{wto} and @var{wfrom}
1488overlap; see @ref{Copying and Concatenation}.
1489
1490The return value is the length of the entire transformed wide character
1491string. This value is not affected by the value of @var{size}, but if
1492it is greater or equal than @var{size}, it means that the transformed
1493wide character string did not entirely fit in the array @var{wto}. In
1494this case, only as much of the wide character string as actually fits
1495was stored. To get the whole transformed wide character string, call
1496@code{wcsxfrm} again with a bigger output array.
1497
1498The transformed wide character string may be longer than the original
1499wide character string, and it may also be shorter.
1500
1501If @var{size} is zero, no characters are stored in @var{to}. In this
1502case, @code{wcsxfrm} simply returns the number of wide characters that
1503would be the length of the transformed wide character string. This is
1504useful for determining what size the allocated array should be (remember
1505to multiply with @code{sizeof (wchar_t)}). It does not matter what
1506@var{wto} is if @var{size} is zero; @var{wto} may even be a null pointer.
28f540f4
RM
1507@end deftypefun
1508
1509Here is an example of how you can use @code{strxfrm} when
1510you plan to do many comparisons. It does the same thing as the previous
1511example, but much faster, because it has to transform each string only
1512once, no matter how many times it is compared with other strings. Even
1513the time needed to allocate and free storage is much less than the time
1514we save, when there are many strings.
1515
1516@smallexample
1517struct sorter @{ char *input; char *transformed; @};
1518
1519/* @r{This is the comparison function used with @code{qsort}}
1520 @r{to sort an array of @code{struct sorter}.} */
1521
1522int
e39745ff 1523compare_elements (const void *v1, const void *v2)
28f540f4 1524@{
e39745ff
AJ
1525 const struct sorter *p1 = v1;
1526 const struct sorter *p2 = v2;
1527
28f540f4
RM
1528 return strcmp (p1->transformed, p2->transformed);
1529@}
1530
1531/* @r{This is the entry point---the function to sort}
1532 @r{strings using the locale's collating sequence.} */
1533
1534void
1535sort_strings_fast (char **array, int nstrings)
1536@{
1537 struct sorter temp_array[nstrings];
1538 int i;
1539
1540 /* @r{Set up @code{temp_array}. Each element contains}
1541 @r{one input string and its transformed string.} */
1542 for (i = 0; i < nstrings; i++)
1543 @{
1544 size_t length = strlen (array[i]) * 2;
a5113b14 1545 char *transformed;
f2ea0f5b 1546 size_t transformed_length;
28f540f4
RM
1547
1548 temp_array[i].input = array[i];
1549
a5113b14
UD
1550 /* @r{First try a buffer perhaps big enough.} */
1551 transformed = (char *) xmalloc (length);
1552
1553 /* @r{Transform @code{array[i]}.} */
1554 transformed_length = strxfrm (transformed, array[i], length);
1555
1556 /* @r{If the buffer was not large enough, resize it}
1557 @r{and try again.} */
1558 if (transformed_length >= length)
28f540f4 1559 @{
a5113b14
UD
1560 /* @r{Allocate the needed space. +1 for terminating}
1561 @r{@code{NUL} character.} */
1562 transformed = (char *) xrealloc (transformed,
1563 transformed_length + 1);
1564
1565 /* @r{The return value is not interesting because we know}
1566 @r{how long the transformed string is.} */
dd7d45e8
UD
1567 (void) strxfrm (transformed, array[i],
1568 transformed_length + 1);
28f540f4 1569 @}
a5113b14
UD
1570
1571 temp_array[i].transformed = transformed;
28f540f4
RM
1572 @}
1573
1574 /* @r{Sort @code{temp_array} by comparing transformed strings.} */
1575 qsort (temp_array, sizeof (struct sorter),
1576 nstrings, compare_elements);
1577
1578 /* @r{Put the elements back in the permanent array}
1579 @r{in their sorted order.} */
1580 for (i = 0; i < nstrings; i++)
1581 array[i] = temp_array[i].input;
1582
1583 /* @r{Free the strings we allocated.} */
1584 for (i = 0; i < nstrings; i++)
1585 free (temp_array[i].transformed);
1586@}
1587@end smallexample
1588
8a2f1f5b
UD
1589The interesting part of this code for the wide character version would
1590look like this:
1591
1592@smallexample
1593void
1594sort_strings_fast (wchar_t **array, int nstrings)
1595@{
1596 @dots{}
1597 /* @r{Transform @code{array[i]}.} */
1598 transformed_length = wcsxfrm (transformed, array[i], length);
1599
1600 /* @r{If the buffer was not large enough, resize it}
1601 @r{and try again.} */
1602 if (transformed_length >= length)
1603 @{
1604 /* @r{Allocate the needed space. +1 for terminating}
1605 @r{@code{NUL} character.} */
1606 transformed = (wchar_t *) xrealloc (transformed,
1607 (transformed_length + 1)
1608 * sizeof (wchar_t));
1609
1610 /* @r{The return value is not interesting because we know}
1611 @r{how long the transformed string is.} */
1612 (void) wcsxfrm (transformed, array[i],
1613 transformed_length + 1);
1614 @}
1615 @dots{}
1616@end smallexample
1617
1618@noindent
1619Note the additional multiplication with @code{sizeof (wchar_t)} in the
1620@code{realloc} call.
1621
1622@strong{Compatibility Note:} The string collation functions are a new
976780fd 1623feature of @w{ISO C90}. Older C dialects have no equivalent feature.
8a2f1f5b
UD
1624The wide character versions were introduced in @w{Amendment 1} to @w{ISO
1625C90}.
28f540f4 1626
b4012b75 1627@node Search Functions
28f540f4
RM
1628@section Search Functions
1629
1630This section describes library functions which perform various kinds
1631of searching operations on strings and arrays. These functions are
1632declared in the header file @file{string.h}.
1633@pindex string.h
1634@cindex search functions (for strings)
1635@cindex string search functions
1636
1637@comment string.h
f65fd747 1638@comment ISO
28f540f4 1639@deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
11087373 1640@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1641This function finds the first occurrence of the byte @var{c} (converted
1642to an @code{unsigned char}) in the initial @var{size} bytes of the
1643object beginning at @var{block}. The return value is a pointer to the
1644located byte, or a null pointer if no match was found.
1645@end deftypefun
1646
8a2f1f5b
UD
1647@comment wchar.h
1648@comment ISO
1649@deftypefun {wchar_t *} wmemchr (const wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
11087373 1650@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1651This function finds the first occurrence of the wide character @var{wc}
1652in the initial @var{size} wide characters of the object beginning at
1653@var{block}. The return value is a pointer to the located wide
1654character, or a null pointer if no match was found.
1655@end deftypefun
1656
87b56f36
UD
1657@comment string.h
1658@comment GNU
1659@deftypefun {void *} rawmemchr (const void *@var{block}, int @var{c})
11087373 1660@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
87b56f36
UD
1661Often the @code{memchr} function is used with the knowledge that the
1662byte @var{c} is available in the memory block specified by the
1663parameters. But this means that the @var{size} parameter is not really
1664needed and that the tests performed with it at runtime (to check whether
1665the end of the block is reached) are not needed.
1666
1667The @code{rawmemchr} function exists for just this situation which is
1668surprisingly frequent. The interface is similar to @code{memchr} except
1669that the @var{size} parameter is missing. The function will look beyond
1670the end of the block pointed to by @var{block} in case the programmer
6be569a4 1671made an error in assuming that the byte @var{c} is present in the block.
87b56f36
UD
1672In this case the result is unspecified. Otherwise the return value is a
1673pointer to the located byte.
1674
1675This function is of special interest when looking for the end of a
1676string. Since all strings are terminated by a null byte a call like
1677
1678@smallexample
1679 rawmemchr (str, '\0')
1680@end smallexample
1681
8a2f1f5b 1682@noindent
87b56f36
UD
1683will never go beyond the end of the string.
1684
1685This function is a GNU extension.
1686@end deftypefun
1687
ca747856
RM
1688@comment string.h
1689@comment GNU
1690@deftypefun {void *} memrchr (const void *@var{block}, int @var{c}, size_t @var{size})
11087373 1691@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
ca747856
RM
1692The function @code{memrchr} is like @code{memchr}, except that it searches
1693backwards from the end of the block defined by @var{block} and @var{size}
1694(instead of forwards from the front).
4efcb713
UD
1695
1696This function is a GNU extension.
a2d63612 1697@end deftypefun
ca747856 1698
28f540f4 1699@comment string.h
f65fd747 1700@comment ISO
28f540f4 1701@deftypefun {char *} strchr (const char *@var{string}, int @var{c})
11087373 1702@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1703The @code{strchr} function finds the first occurrence of the character
1704@var{c} (converted to a @code{char}) in the null-terminated string
1705beginning at @var{string}. The return value is a pointer to the located
1706character, or a null pointer if no match was found.
1707
1708For example,
1709@smallexample
1710strchr ("hello, world", 'l')
1711 @result{} "llo, world"
1712strchr ("hello, world", '?')
1713 @result{} NULL
a5113b14 1714@end smallexample
28f540f4
RM
1715
1716The terminating null character is considered to be part of the string,
1717so you can use this function get a pointer to the end of a string by
0520adde
FB
1718specifying a null character as the value of the @var{c} argument.
1719
1720When @code{strchr} returns a null pointer, it does not let you know
1721the position of the terminating null character it has found. If you
1722need that information, it is better (but less portable) to use
1723@code{strchrnul} than to search for it a second time.
8a2f1f5b
UD
1724@end deftypefun
1725
1726@comment wchar.h
1727@comment ISO
1728@deftypefun {wchar_t *} wcschr (const wchar_t *@var{wstring}, int @var{wc})
11087373 1729@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1730The @code{wcschr} function finds the first occurrence of the wide
1731character @var{wc} in the null-terminated wide character string
1732beginning at @var{wstring}. The return value is a pointer to the
1733located wide character, or a null pointer if no match was found.
1734
1735The terminating null character is considered to be part of the wide
1736character string, so you can use this function get a pointer to the end
1737of a wide character string by specifying a null wude character as the
1738value of the @var{wc} argument. It would be better (but less portable)
1739to use @code{wcschrnul} in this case, though.
28f540f4
RM
1740@end deftypefun
1741
1742@comment string.h
87b56f36 1743@comment GNU
0e4ee106 1744@deftypefun {char *} strchrnul (const char *@var{string}, int @var{c})
11087373 1745@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
0e4ee106 1746@code{strchrnul} is the same as @code{strchr} except that if it does
ec28fc7c 1747not find the character, it returns a pointer to string's terminating
0e4ee106 1748null character rather than a null pointer.
8a2f1f5b
UD
1749
1750This function is a GNU extension.
1751@end deftypefun
1752
1753@comment wchar.h
1754@comment GNU
1755@deftypefun {wchar_t *} wcschrnul (const wchar_t *@var{wstring}, wchar_t @var{wc})
11087373 1756@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1757@code{wcschrnul} is the same as @code{wcschr} except that if it does not
1758find the wide character, it returns a pointer to wide character string's
1759terminating null wide character rather than a null pointer.
1760
1761This function is a GNU extension.
28f540f4
RM
1762@end deftypefun
1763
ec28fc7c 1764One useful, but unusual, use of the @code{strchr}
ee2752ea
UD
1765function is when one wants to have a pointer pointing to the NUL byte
1766terminating a string. This is often written in this way:
1767
1768@smallexample
1769 s += strlen (s);
1770@end smallexample
1771
1772@noindent
1773This is almost optimal but the addition operation duplicated a bit of
1774the work already done in the @code{strlen} function. A better solution
1775is this:
1776
1777@smallexample
1778 s = strchr (s, '\0');
1779@end smallexample
1780
1781There is no restriction on the second parameter of @code{strchr} so it
1782could very well also be the NUL character. Those readers thinking very
1783hard about this might now point out that the @code{strchr} function is
8c474db5 1784more expensive than the @code{strlen} function since we have two abort
1f77f049 1785criteria. This is right. But in @theglibc{} the implementation of
0e4ee106 1786@code{strchr} is optimized in a special way so that @code{strchr}
8c474db5 1787actually is faster.
ee2752ea 1788
28f540f4 1789@comment string.h
f65fd747 1790@comment ISO
28f540f4 1791@deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
11087373 1792@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1793The function @code{strrchr} is like @code{strchr}, except that it searches
1794backwards from the end of the string @var{string} (instead of forwards
1795from the front).
1796
1797For example,
1798@smallexample
1799strrchr ("hello, world", 'l')
1800 @result{} "ld"
1801@end smallexample
1802@end deftypefun
1803
8a2f1f5b
UD
1804@comment wchar.h
1805@comment ISO
1806@deftypefun {wchar_t *} wcsrchr (const wchar_t *@var{wstring}, wchar_t @var{c})
11087373 1807@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1808The function @code{wcsrchr} is like @code{wcschr}, except that it searches
1809backwards from the end of the string @var{wstring} (instead of forwards
1810from the front).
1811@end deftypefun
1812
28f540f4 1813@comment string.h
f65fd747 1814@comment ISO
28f540f4 1815@deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
11087373 1816@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1817This is like @code{strchr}, except that it searches @var{haystack} for a
1818substring @var{needle} rather than just a single character. It
1819returns a pointer into the string @var{haystack} that is the first
1820character of the substring, or a null pointer if no match was found. If
1821@var{needle} is an empty string, the function returns @var{haystack}.
1822
1823For example,
1824@smallexample
1825strstr ("hello, world", "l")
1826 @result{} "llo, world"
1827strstr ("hello, world", "wo")
1828 @result{} "world"
1829@end smallexample
1830@end deftypefun
1831
8a2f1f5b
UD
1832@comment wchar.h
1833@comment ISO
1834@deftypefun {wchar_t *} wcsstr (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
11087373 1835@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1836This is like @code{wcschr}, except that it searches @var{haystack} for a
1837substring @var{needle} rather than just a single wide character. It
1838returns a pointer into the string @var{haystack} that is the first wide
1839character of the substring, or a null pointer if no match was found. If
1840@var{needle} is an empty string, the function returns @var{haystack}.
1841@end deftypefun
1842
1843@comment wchar.h
1844@comment XPG
1845@deftypefun {wchar_t *} wcswcs (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
11087373 1846@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
9dcc8f11 1847@code{wcswcs} is a deprecated alias for @code{wcsstr}. This is the
8a2f1f5b
UD
1848name originally used in the X/Open Portability Guide before the
1849@w{Amendment 1} to @w{ISO C90} was published.
1850@end deftypefun
1851
28f540f4 1852
0e4ee106 1853@comment string.h
8a2f1f5b 1854@comment GNU
0e4ee106 1855@deftypefun {char *} strcasestr (const char *@var{haystack}, const char *@var{needle})
11087373
AO
1856@safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1857@c There may be multiple calls of strncasecmp, each accessing the locale
1858@c object independently.
0e4ee106
UD
1859This is like @code{strstr}, except that it ignores case in searching for
1860the substring. Like @code{strcasecmp}, it is locale dependent how
1861uppercase and lowercase characters are related.
1862
1863
1864For example,
1865@smallexample
d6868416 1866strcasestr ("hello, world", "L")
0e4ee106 1867 @result{} "llo, world"
d6868416 1868strcasestr ("hello, World", "wo")
0e4ee106
UD
1869 @result{} "World"
1870@end smallexample
1871@end deftypefun
1872
1873
28f540f4
RM
1874@comment string.h
1875@comment GNU
63551311 1876@deftypefun {void *} memmem (const void *@var{haystack}, size_t @var{haystack-len},@*const void *@var{needle}, size_t @var{needle-len})
11087373 1877@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1878This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
1879arrays rather than null-terminated strings. @var{needle-len} is the
1880length of @var{needle} and @var{haystack-len} is the length of
1881@var{haystack}.@refill
1882
1883This function is a GNU extension.
1884@end deftypefun
1885
1886@comment string.h
f65fd747 1887@comment ISO
28f540f4 1888@deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
11087373 1889@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1890The @code{strspn} (``string span'') function returns the length of the
1891initial substring of @var{string} that consists entirely of characters that
1892are members of the set specified by the string @var{skipset}. The order
1893of the characters in @var{skipset} is not important.
1894
1895For example,
1896@smallexample
1897strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
1898 @result{} 5
1899@end smallexample
8a2f1f5b
UD
1900
1901Note that ``character'' is here used in the sense of byte. In a string
1902using a multibyte character encoding (abstract) character consisting of
1903more than one byte are not treated as an entity. Each byte is treated
1904separately. The function is not locale-dependent.
1905@end deftypefun
1906
1907@comment wchar.h
1908@comment ISO
1909@deftypefun size_t wcsspn (const wchar_t *@var{wstring}, const wchar_t *@var{skipset})
11087373 1910@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1911The @code{wcsspn} (``wide character string span'') function returns the
1912length of the initial substring of @var{wstring} that consists entirely
1913of wide characters that are members of the set specified by the string
1914@var{skipset}. The order of the wide characters in @var{skipset} is not
1915important.
28f540f4
RM
1916@end deftypefun
1917
1918@comment string.h
f65fd747 1919@comment ISO
28f540f4 1920@deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
11087373 1921@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1922The @code{strcspn} (``string complement span'') function returns the length
1923of the initial substring of @var{string} that consists entirely of characters
1924that are @emph{not} members of the set specified by the string @var{stopset}.
1925(In other words, it returns the offset of the first character in @var{string}
1926that is a member of the set @var{stopset}.)
1927
1928For example,
1929@smallexample
1930strcspn ("hello, world", " \t\n,.;!?")
1931 @result{} 5
1932@end smallexample
8a2f1f5b
UD
1933
1934Note that ``character'' is here used in the sense of byte. In a string
1935using a multibyte character encoding (abstract) character consisting of
1936more than one byte are not treated as an entity. Each byte is treated
1937separately. The function is not locale-dependent.
1938@end deftypefun
1939
1940@comment wchar.h
1941@comment ISO
1942@deftypefun size_t wcscspn (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
11087373 1943@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1944The @code{wcscspn} (``wide character string complement span'') function
1945returns the length of the initial substring of @var{wstring} that
1946consists entirely of wide characters that are @emph{not} members of the
1947set specified by the string @var{stopset}. (In other words, it returns
1948the offset of the first character in @var{string} that is a member of
1949the set @var{stopset}.)
28f540f4
RM
1950@end deftypefun
1951
1952@comment string.h
f65fd747 1953@comment ISO
28f540f4 1954@deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
11087373 1955@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
1956The @code{strpbrk} (``string pointer break'') function is related to
1957@code{strcspn}, except that it returns a pointer to the first character
1958in @var{string} that is a member of the set @var{stopset} instead of the
1959length of the initial substring. It returns a null pointer if no such
1960character from @var{stopset} is found.
1961
1962@c @group Invalid outside the example.
1963For example,
1964
1965@smallexample
1966strpbrk ("hello, world", " \t\n,.;!?")
1967 @result{} ", world"
1968@end smallexample
1969@c @end group
8a2f1f5b
UD
1970
1971Note that ``character'' is here used in the sense of byte. In a string
1972using a multibyte character encoding (abstract) character consisting of
1973more than one byte are not treated as an entity. Each byte is treated
1974separately. The function is not locale-dependent.
1975@end deftypefun
1976
1977@comment wchar.h
1978@comment ISO
1979@deftypefun {wchar_t *} wcspbrk (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
11087373 1980@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
1981The @code{wcspbrk} (``wide character string pointer break'') function is
1982related to @code{wcscspn}, except that it returns a pointer to the first
1983wide character in @var{wstring} that is a member of the set
1984@var{stopset} instead of the length of the initial substring. It
1985returns a null pointer if no such character from @var{stopset} is found.
28f540f4
RM
1986@end deftypefun
1987
0e4ee106
UD
1988
1989@subsection Compatibility String Search Functions
1990
1991@comment string.h
1992@comment BSD
1993@deftypefun {char *} index (const char *@var{string}, int @var{c})
11087373 1994@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
0e4ee106
UD
1995@code{index} is another name for @code{strchr}; they are exactly the same.
1996New code should always use @code{strchr} since this name is defined in
1997@w{ISO C} while @code{index} is a BSD invention which never was available
1998on @w{System V} derived systems.
1999@end deftypefun
2000
2001@comment string.h
2002@comment BSD
2003@deftypefun {char *} rindex (const char *@var{string}, int @var{c})
11087373 2004@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
0e4ee106
UD
2005@code{rindex} is another name for @code{strrchr}; they are exactly the same.
2006New code should always use @code{strrchr} since this name is defined in
2007@w{ISO C} while @code{rindex} is a BSD invention which never was available
2008on @w{System V} derived systems.
2009@end deftypefun
2010
b4012b75 2011@node Finding Tokens in a String
28f540f4
RM
2012@section Finding Tokens in a String
2013
28f540f4
RM
2014@cindex tokenizing strings
2015@cindex breaking a string into tokens
2016@cindex parsing tokens from a string
2017It's fairly common for programs to have a need to do some simple kinds
2018of lexical analysis and parsing, such as splitting a command string up
2019into tokens. You can do this with the @code{strtok} function, declared
2020in the header file @file{string.h}.
2021@pindex string.h
2022
2023@comment string.h
f65fd747 2024@comment ISO
8a2f1f5b 2025@deftypefun {char *} strtok (char *restrict @var{newstring}, const char *restrict @var{delimiters})
11087373 2026@safety{@prelim{}@mtunsafe{@mtasurace{:strtok}}@asunsafe{}@acsafe{}}
28f540f4
RM
2027A string can be split into tokens by making a series of calls to the
2028function @code{strtok}.
2029
2030The string to be split up is passed as the @var{newstring} argument on
2031the first call only. The @code{strtok} function uses this to set up
2032some internal state information. Subsequent calls to get additional
2033tokens from the same string are indicated by passing a null pointer as
2034the @var{newstring} argument. Calling @code{strtok} with another
2035non-null @var{newstring} argument reinitializes the state information.
2036It is guaranteed that no other library function ever calls @code{strtok}
2037behind your back (which would mess up this internal state information).
2038
2039The @var{delimiters} argument is a string that specifies a set of delimiters
2040that may surround the token being extracted. All the initial characters
2041that are members of this set are discarded. The first character that is
2042@emph{not} a member of this set of delimiters marks the beginning of the
2043next token. The end of the token is found by looking for the next
2044character that is a member of the delimiter set. This character in the
2045original string @var{newstring} is overwritten by a null character, and the
2046pointer to the beginning of the token in @var{newstring} is returned.
2047
2048On the next call to @code{strtok}, the searching begins at the next
2049character beyond the one that marked the end of the previous token.
2050Note that the set of delimiters @var{delimiters} do not have to be the
2051same on every call in a series of calls to @code{strtok}.
2052
2053If the end of the string @var{newstring} is reached, or if the remainder of
2054string consists only of delimiter characters, @code{strtok} returns
2055a null pointer.
8a2f1f5b 2056
8a2f1f5b
UD
2057Note that ``character'' is here used in the sense of byte. In a string
2058using a multibyte character encoding (abstract) character consisting of
2059more than one byte are not treated as an entity. Each byte is treated
2060separately. The function is not locale-dependent.
2061@end deftypefun
2062
2063@comment wchar.h
2064@comment ISO
1acd4371 2065@deftypefun {wchar_t *} wcstok (wchar_t *@var{newstring}, const wchar_t *@var{delimiters}, wchar_t **@var{save_ptr})
11087373 2066@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
8a2f1f5b
UD
2067A string can be split into tokens by making a series of calls to the
2068function @code{wcstok}.
2069
2070The string to be split up is passed as the @var{newstring} argument on
2071the first call only. The @code{wcstok} function uses this to set up
2072some internal state information. Subsequent calls to get additional
2073tokens from the same wide character string are indicated by passing a
1acd4371
AO
2074null pointer as the @var{newstring} argument, which causes the pointer
2075previously stored in @var{save_ptr} to be used instead.
8a2f1f5b
UD
2076
2077The @var{delimiters} argument is a wide character string that specifies
2078a set of delimiters that may surround the token being extracted. All
2079the initial wide characters that are members of this set are discarded.
2080The first wide character that is @emph{not} a member of this set of
2081delimiters marks the beginning of the next token. The end of the token
2082is found by looking for the next wide character that is a member of the
2083delimiter set. This wide character in the original wide character
1acd4371
AO
2084string @var{newstring} is overwritten by a null wide character, the
2085pointer past the overwritten wide character is saved in @var{save_ptr},
2086and the pointer to the beginning of the token in @var{newstring} is
2087returned.
8a2f1f5b
UD
2088
2089On the next call to @code{wcstok}, the searching begins at the next
2090wide character beyond the one that marked the end of the previous token.
2091Note that the set of delimiters @var{delimiters} do not have to be the
2092same on every call in a series of calls to @code{wcstok}.
2093
2094If the end of the wide character string @var{newstring} is reached, or
2095if the remainder of string consists only of delimiter wide characters,
2096@code{wcstok} returns a null pointer.
28f540f4
RM
2097@end deftypefun
2098
8a2f1f5b
UD
2099@strong{Warning:} Since @code{strtok} and @code{wcstok} alter the string
2100they is parsing, you should always copy the string to a temporary buffer
2101before parsing it with @code{strtok}/@code{wcstok} (@pxref{Copying and
2102Concatenation}). If you allow @code{strtok} or @code{wcstok} to modify
2103a string that came from another part of your program, you are asking for
2104trouble; that string might be used for other purposes after
2105@code{strtok} or @code{wcstok} has modified it, and it would not have
2106the expected value.
28f540f4
RM
2107
2108The string that you are operating on might even be a constant. Then
8a2f1f5b
UD
2109when @code{strtok} or @code{wcstok} tries to modify it, your program
2110will get a fatal signal for writing in read-only memory. @xref{Program
2111Error Signals}. Even if the operation of @code{strtok} or @code{wcstok}
2112would not require a modification of the string (e.g., if there is
1f77f049 2113exactly one token) the string can (and in the @glibcadj{} case will) be
8a2f1f5b 2114modified.
28f540f4
RM
2115
2116This is a special case of a general principle: if a part of a program
2117does not have as its purpose the modification of a certain data
2118structure, then it is error-prone to modify the data structure
2119temporarily.
2120
1acd4371 2121The function @code{strtok} is not reentrant, whereas @code{wcstok} is.
8a2f1f5b
UD
2122@xref{Nonreentrancy}, for a discussion of where and why reentrancy is
2123important.
28f540f4
RM
2124
2125Here is a simple example showing the use of @code{strtok}.
2126
2127@comment Yes, this example has been tested.
2128@smallexample
2129#include <string.h>
2130#include <stddef.h>
2131
2132@dots{}
2133
5649a1d6 2134const char string[] = "words separated by spaces -- and, punctuation!";
28f540f4 2135const char delimiters[] = " .,;:!-";
5649a1d6 2136char *token, *cp;
28f540f4
RM
2137
2138@dots{}
2139
5649a1d6
UD
2140cp = strdupa (string); /* Make writable copy. */
2141token = strtok (cp, delimiters); /* token => "words" */
28f540f4
RM
2142token = strtok (NULL, delimiters); /* token => "separated" */
2143token = strtok (NULL, delimiters); /* token => "by" */
2144token = strtok (NULL, delimiters); /* token => "spaces" */
2145token = strtok (NULL, delimiters); /* token => "and" */
2146token = strtok (NULL, delimiters); /* token => "punctuation" */
2147token = strtok (NULL, delimiters); /* token => NULL */
2148@end smallexample
a5113b14 2149
1f77f049 2150@Theglibc{} contains two more functions for tokenizing a string
8a2f1f5b
UD
2151which overcome the limitation of non-reentrancy. They are only
2152available for multibyte character strings.
a5113b14
UD
2153
2154@comment string.h
2155@comment POSIX
2156@deftypefun {char *} strtok_r (char *@var{newstring}, const char *@var{delimiters}, char **@var{save_ptr})
11087373 2157@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
dd7d45e8
UD
2158Just like @code{strtok}, this function splits the string into several
2159tokens which can be accessed by successive calls to @code{strtok_r}.
1acd4371
AO
2160The difference is that, as in @code{wcstok}, the information about the
2161next token is stored in the space pointed to by the third argument,
2162@var{save_ptr}, which is a pointer to a string pointer. Calling
2163@code{strtok_r} with a null pointer for @var{newstring} and leaving
2164@var{save_ptr} between the calls unchanged does the job without
2165hindering reentrancy.
a5113b14 2166
976780fd 2167This function is defined in POSIX.1 and can be found on many systems
a5113b14
UD
2168which support multi-threading.
2169@end deftypefun
2170
2171@comment string.h
2172@comment BSD
2173@deftypefun {char *} strsep (char **@var{string_ptr}, const char *@var{delimiter})
11087373 2174@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
0050ad5f
UD
2175This function has a similar functionality as @code{strtok_r} with the
2176@var{newstring} argument replaced by the @var{save_ptr} argument. The
2177initialization of the moving pointer has to be done by the user.
2178Successive calls to @code{strsep} move the pointer along the tokens
2179separated by @var{delimiter}, returning the address of the next token
2180and updating @var{string_ptr} to point to the beginning of the next
2181token.
2182
2183One difference between @code{strsep} and @code{strtok_r} is that if the
2184input string contains more than one character from @var{delimiter} in a
2185row @code{strsep} returns an empty string for each pair of characters
2186from @var{delimiter}. This means that a program normally should test
2187for @code{strsep} returning an empty string before processing it.
9afc8a59 2188
a5113b14
UD
2189This function was introduced in 4.3BSD and therefore is widely available.
2190@end deftypefun
2191
2192Here is how the above example looks like when @code{strsep} is used.
2193
2194@comment Yes, this example has been tested.
2195@smallexample
2196#include <string.h>
2197#include <stddef.h>
2198
2199@dots{}
2200
5649a1d6 2201const char string[] = "words separated by spaces -- and, punctuation!";
a5113b14
UD
2202const char delimiters[] = " .,;:!-";
2203char *running;
2204char *token;
2205
2206@dots{}
2207
5649a1d6 2208running = strdupa (string);
a5113b14
UD
2209token = strsep (&running, delimiters); /* token => "words" */
2210token = strsep (&running, delimiters); /* token => "separated" */
2211token = strsep (&running, delimiters); /* token => "by" */
2212token = strsep (&running, delimiters); /* token => "spaces" */
9afc8a59
UD
2213token = strsep (&running, delimiters); /* token => "" */
2214token = strsep (&running, delimiters); /* token => "" */
2215token = strsep (&running, delimiters); /* token => "" */
a5113b14 2216token = strsep (&running, delimiters); /* token => "and" */
9afc8a59 2217token = strsep (&running, delimiters); /* token => "" */
a5113b14 2218token = strsep (&running, delimiters); /* token => "punctuation" */
9afc8a59 2219token = strsep (&running, delimiters); /* token => "" */
a5113b14
UD
2220token = strsep (&running, delimiters); /* token => NULL */
2221@end smallexample
b4012b75 2222
ec28fc7c
UD
2223@comment string.h
2224@comment GNU
2225@deftypefun {char *} basename (const char *@var{filename})
11087373 2226@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
ec28fc7c 2227The GNU version of the @code{basename} function returns the last
9442cd75 2228component of the path in @var{filename}. This function is the preferred
ec28fc7c
UD
2229usage, since it does not modify the argument, @var{filename}, and
2230respects trailing slashes. The prototype for @code{basename} can be
2231found in @file{string.h}. Note, this function is overriden by the XPG
2232version, if @file{libgen.h} is included.
2233
2234Example of using GNU @code{basename}:
2235
2236@smallexample
2237#include <string.h>
2238
2239int
2240main (int argc, char *argv[])
2241@{
2242 char *prog = basename (argv[0]);
2243
2244 if (argc < 2)
2245 @{
2246 fprintf (stderr, "Usage %s <arg>\n", prog);
2247 exit (1);
2248 @}
2249
2250 @dots{}
2251@}
2252@end smallexample
2253
2254@strong{Portability Note:} This function may produce different results
2255on different systems.
2256
2257@end deftypefun
2258
2259@comment libgen.h
2260@comment XPG
8ded91fb 2261@deftypefun {char *} basename (const char *@var{path})
11087373 2262@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
ec28fc7c
UD
2263This is the standard XPG defined @code{basename}. It is similar in
2264spirit to the GNU version, but may modify the @var{path} by removing
2265trailing '/' characters. If the @var{path} is made up entirely of '/'
2266characters, then "/" will be returned. Also, if @var{path} is
2267@code{NULL} or an empty string, then "." is returned. The prototype for
e4a5f77d 2268the XPG version can be found in @file{libgen.h}.
ec28fc7c
UD
2269
2270Example of using XPG @code{basename}:
2271
2272@smallexample
2273#include <libgen.h>
2274
2275int
2276main (int argc, char *argv[])
2277@{
2278 char *prog;
2279 char *path = strdupa (argv[0]);
2280
2281 prog = basename (path);
2282
2283 if (argc < 2)
2284 @{
2285 fprintf (stderr, "Usage %s <arg>\n", prog);
2286 exit (1);
2287 @}
2288
2289 @dots{}
2290
2291@}
2292@end smallexample
2293@end deftypefun
2294
2295@comment libgen.h
2296@comment XPG
2297@deftypefun {char *} dirname (char *@var{path})
11087373 2298@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
ec28fc7c
UD
2299The @code{dirname} function is the compliment to the XPG version of
2300@code{basename}. It returns the parent directory of the file specified
2301by @var{path}. If @var{path} is @code{NULL}, an empty string, or
2302contains no '/' characters, then "." is returned. The prototype for this
2303function can be found in @file{libgen.h}.
2304@end deftypefun
0e4ee106
UD
2305
2306@node strfry
2307@section strfry
2308
2309The function below addresses the perennial programming quandary: ``How do
2310I take good data in string form and painlessly turn it into garbage?''
2311This is actually a fairly simple task for C programmers who do not use
1f77f049
JM
2312@theglibc{} string functions, but for programs based on @theglibc{},
2313the @code{strfry} function is the preferred method for
0e4ee106
UD
2314destroying string data.
2315
2316The prototype for this function is in @file{string.h}.
2317
2318@comment string.h
2319@comment GNU
ec28fc7c 2320@deftypefun {char *} strfry (char *@var{string})
11087373
AO
2321@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2322@c Calls initstate_r, time, getpid, strlen, and random_r.
0e4ee106
UD
2323
2324@code{strfry} creates a pseudorandom anagram of a string, replacing the
2325input with the anagram in place. For each position in the string,
2326@code{strfry} swaps it with a position in the string selected at random
2327(from a uniform distribution). The two positions may be the same.
2328
2329The return value of @code{strfry} is always @var{string}.
2330
1f77f049 2331@strong{Portability Note:} This function is unique to @theglibc{}.
0e4ee106
UD
2332
2333@end deftypefun
2334
2335
2336@node Trivial Encryption
2337@section Trivial Encryption
2338@cindex encryption
2339
2340
2341The @code{memfrob} function converts an array of data to something
2342unrecognizable and back again. It is not encryption in its usual sense
2343since it is easy for someone to convert the encrypted data back to clear
2344text. The transformation is analogous to Usenet's ``Rot13'' encryption
2345method for obscuring offensive jokes from sensitive eyes and such.
2346Unlike Rot13, @code{memfrob} works on arbitrary binary data, not just
2347text.
2348@cindex Rot13
2349
2350For true encryption, @xref{Cryptographic Functions}.
2351
2352This function is declared in @file{string.h}.
2353@pindex string.h
2354
2355@comment string.h
2356@comment GNU
2357@deftypefun {void *} memfrob (void *@var{mem}, size_t @var{length})
11087373 2358@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
0e4ee106
UD
2359
2360@code{memfrob} transforms (frobnicates) each byte of the data structure
2361at @var{mem}, which is @var{length} bytes long, by bitwise exclusive
2362oring it with binary 00101010. It does the transformation in place and
2363its return value is always @var{mem}.
2364
2365Note that @code{memfrob} a second time on the same data structure
2366returns it to its original state.
2367
2368This is a good function for hiding information from someone who doesn't
2369want to see it or doesn't want to see it very much. To really prevent
2370people from retrieving the information, use stronger encryption such as
2371that described in @xref{Cryptographic Functions}.
2372
1f77f049 2373@strong{Portability Note:} This function is unique to @theglibc{}.
0e4ee106
UD
2374
2375@end deftypefun
2376
b4012b75
UD
2377@node Encode Binary Data
2378@section Encode Binary Data
2379
2380To store or transfer binary data in environments which only support text
2381one has to encode the binary data by mapping the input bytes to
9dcc8f11 2382characters in the range allowed for storing or transferring. SVID
dd7d45e8
UD
2383systems (and nowadays XPG compliant systems) provide minimal support for
2384this task.
b4012b75
UD
2385
2386@comment stdlib.h
2387@comment XPG
2388@deftypefun {char *} l64a (long int @var{n})
11087373 2389@safety{@prelim{}@mtunsafe{@mtasurace{:l64a}}@asunsafe{}@acsafe{}}
dd7d45e8 2390This function encodes a 32-bit input value using characters from the
290639c3 2391basic character set. It returns a pointer to a 7 character buffer which
dd7d45e8
UD
2392contains an encoded version of @var{n}. To encode a series of bytes the
2393user must copy the returned string to a destination buffer. It returns
2394the empty string if @var{n} is zero, which is somewhat bizarre but
2395mandated by the standard.@*
2396@strong{Warning:} Since a static buffer is used this function should not
5649a1d6 2397be used in multi-threaded programs. There is no thread-safe alternative
dd7d45e8
UD
2398to this function in the C library.@*
2399@strong{Compatibility Note:} The XPG standard states that the return
2400value of @code{l64a} is undefined if @var{n} is negative. In the GNU
2401implementation, @code{l64a} treats its argument as unsigned, so it will
2402return a sensible encoding for any nonzero @var{n}; however, portable
2403programs should not rely on this.
b4012b75 2404
dd7d45e8
UD
2405To encode a large buffer @code{l64a} must be called in a loop, once for
2406each 32-bit word of the buffer. For example, one could do something
2407like this:
5649a1d6
UD
2408
2409@smallexample
2410char *
2411encode (const void *buf, size_t len)
2412@{
2413 /* @r{We know in advance how long the buffer has to be.} */
2414 unsigned char *in = (unsigned char *) buf;
2415 char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
290639c3 2416 char *cp = out, *p;
5649a1d6
UD
2417
2418 /* @r{Encode the length.} */
dd7d45e8 2419 /* @r{Using `htonl' is necessary so that the data can be}
290639c3
UD
2420 @r{decoded even on machines with different byte order.}
2421 @r{`l64a' can return a string shorter than 6 bytes, so }
2422 @r{we pad it with encoding of 0 (}'.'@r{) at the end by }
2423 @r{hand.} */
dd7d45e8 2424
290639c3
UD
2425 p = stpcpy (cp, l64a (htonl (len)));
2426 cp = mempcpy (p, "......", 6 - (p - cp));
5649a1d6
UD
2427
2428 while (len > 3)
2429 @{
2430 unsigned long int n = *in++;
2431 n = (n << 8) | *in++;
2432 n = (n << 8) | *in++;
2433 n = (n << 8) | *in++;
2434 len -= 4;
290639c3
UD
2435 p = stpcpy (cp, l64a (htonl (n)));
2436 cp = mempcpy (p, "......", 6 - (p - cp));
5649a1d6
UD
2437 @}
2438 if (len > 0)
2439 @{
2440 unsigned long int n = *in++;
2441 if (--len > 0)
2442 @{
2443 n = (n << 8) | *in++;
2444 if (--len > 0)
2445 n = (n << 8) | *in;
2446 @}
290639c3 2447 cp = stpcpy (cp, l64a (htonl (n)));
5649a1d6
UD
2448 @}
2449 *cp = '\0';
2450 return out;
2451@}
2452@end smallexample
2453
2454It is strange that the library does not provide the complete
dd7d45e8
UD
2455functionality needed but so be it.
2456
2457@end deftypefun
5649a1d6 2458
b4012b75
UD
2459To decode data produced with @code{l64a} the following function should be
2460used.
2461
5649a1d6
UD
2462@comment stdlib.h
2463@comment XPG
b4012b75 2464@deftypefun {long int} a64l (const char *@var{string})
11087373 2465@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
b4012b75 2466The parameter @var{string} should contain a string which was produced by
dd7d45e8
UD
2467a call to @code{l64a}. The function processes at least 6 characters of
2468this string, and decodes the characters it finds according to the table
2469below. It stops decoding when it finds a character not in the table,
2470rather like @code{atoi}; if you have a buffer which has been broken into
2471lines, you must be careful to skip over the end-of-line characters.
2472
2473The decoded number is returned as a @code{long int} value.
b4012b75 2474@end deftypefun
b13927da 2475
dd7d45e8
UD
2476The @code{l64a} and @code{a64l} functions use a base 64 encoding, in
2477which each character of an encoded string represents six bits of an
2478input word. These symbols are used for the base 64 digits:
2479
2480@multitable {xxxxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx}
2481@item @tab 0 @tab 1 @tab 2 @tab 3 @tab 4 @tab 5 @tab 6 @tab 7
2482@item 0 @tab @code{.} @tab @code{/} @tab @code{0} @tab @code{1}
2483 @tab @code{2} @tab @code{3} @tab @code{4} @tab @code{5}
2484@item 8 @tab @code{6} @tab @code{7} @tab @code{8} @tab @code{9}
2485 @tab @code{A} @tab @code{B} @tab @code{C} @tab @code{D}
2486@item 16 @tab @code{E} @tab @code{F} @tab @code{G} @tab @code{H}
2487 @tab @code{I} @tab @code{J} @tab @code{K} @tab @code{L}
2488@item 24 @tab @code{M} @tab @code{N} @tab @code{O} @tab @code{P}
2489 @tab @code{Q} @tab @code{R} @tab @code{S} @tab @code{T}
2490@item 32 @tab @code{U} @tab @code{V} @tab @code{W} @tab @code{X}
2491 @tab @code{Y} @tab @code{Z} @tab @code{a} @tab @code{b}
2492@item 40 @tab @code{c} @tab @code{d} @tab @code{e} @tab @code{f}
2493 @tab @code{g} @tab @code{h} @tab @code{i} @tab @code{j}
2494@item 48 @tab @code{k} @tab @code{l} @tab @code{m} @tab @code{n}
2495 @tab @code{o} @tab @code{p} @tab @code{q} @tab @code{r}
2496@item 56 @tab @code{s} @tab @code{t} @tab @code{u} @tab @code{v}
2497 @tab @code{w} @tab @code{x} @tab @code{y} @tab @code{z}
2498@end multitable
2499
2500This encoding scheme is not standard. There are some other encoding
2501methods which are much more widely used (UU encoding, MIME encoding).
2502Generally, it is better to use one of these encodings.
2503
b13927da
UD
2504@node Argz and Envz Vectors
2505@section Argz and Envz Vectors
2506
5649a1d6 2507@cindex argz vectors (string vectors)
b13927da
UD
2508@cindex string vectors, null-character separated
2509@cindex argument vectors, null-character separated
2510@dfn{argz vectors} are vectors of strings in a contiguous block of
2511memory, each element separated from its neighbors by null-characters
2512(@code{'\0'}).
2513
5649a1d6 2514@cindex envz vectors (environment vectors)
b13927da
UD
2515@cindex environment vectors, null-character separated
2516@dfn{Envz vectors} are an extension of argz vectors where each element is a
5649a1d6 2517name-value pair, separated by a @code{'='} character (as in a Unix
b13927da
UD
2518environment).
2519
2520@menu
2521* Argz Functions:: Operations on argz vectors.
2522* Envz Functions:: Additional operations on environment vectors.
2523@end menu
2524
2525@node Argz Functions, Envz Functions, , Argz and Envz Vectors
2526@subsection Argz Functions
2527
2528Each argz vector is represented by a pointer to the first element, of
2529type @code{char *}, and a size, of type @code{size_t}, both of which can
2530be initialized to @code{0} to represent an empty argz vector. All argz
2531functions accept either a pointer and a size argument, or pointers to
2532them, if they will be modified.
2533
2534The argz functions use @code{malloc}/@code{realloc} to allocate/grow
2535argz vectors, and so any argz vector creating using these functions may
2536be freed by using @code{free}; conversely, any argz function that may
2537grow a string expects that string to have been allocated using
2538@code{malloc} (those argz functions that only examine their arguments or
2539modify them in place will work on any sort of memory).
2540@xref{Unconstrained Allocation}.
2541
2542All argz functions that do memory allocation have a return type of
2543@code{error_t}, and return @code{0} for success, and @code{ENOMEM} if an
2544allocation error occurs.
2545
2546@pindex argz.h
2547These functions are declared in the standard include file @file{argz.h}.
2548
5649a1d6
UD
2549@comment argz.h
2550@comment GNU
b13927da 2551@deftypefun {error_t} argz_create (char *const @var{argv}[], char **@var{argz}, size_t *@var{argz_len})
11087373 2552@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
5649a1d6 2553The @code{argz_create} function converts the Unix-style argument vector
b13927da
UD
2554@var{argv} (a vector of pointers to normal C strings, terminated by
2555@code{(char *)0}; @pxref{Program Arguments}) into an argz vector with
2556the same elements, which is returned in @var{argz} and @var{argz_len}.
2557@end deftypefun
2558
5649a1d6
UD
2559@comment argz.h
2560@comment GNU
b13927da 2561@deftypefun {error_t} argz_create_sep (const char *@var{string}, int @var{sep}, char **@var{argz}, size_t *@var{argz_len})
11087373 2562@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
b13927da
UD
2563The @code{argz_create_sep} function converts the null-terminated string
2564@var{string} into an argz vector (returned in @var{argz} and
49c091e5 2565@var{argz_len}) by splitting it into elements at every occurrence of the
b13927da
UD
2566character @var{sep}.
2567@end deftypefun
2568
5649a1d6
UD
2569@comment argz.h
2570@comment GNU
b13927da 2571@deftypefun {size_t} argz_count (const char *@var{argz}, size_t @var{arg_len})
11087373 2572@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
b13927da
UD
2573Returns the number of elements in the argz vector @var{argz} and
2574@var{argz_len}.
2575@end deftypefun
2576
5649a1d6
UD
2577@comment argz.h
2578@comment GNU
8ded91fb 2579@deftypefun {void} argz_extract (const char *@var{argz}, size_t @var{argz_len}, char **@var{argv})
11087373 2580@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
b13927da 2581The @code{argz_extract} function converts the argz vector @var{argz} and
5649a1d6 2582@var{argz_len} into a Unix-style argument vector stored in @var{argv},
b13927da
UD
2583by putting pointers to every element in @var{argz} into successive
2584positions in @var{argv}, followed by a terminator of @code{0}.
2585@var{Argv} must be pre-allocated with enough space to hold all the
2586elements in @var{argz} plus the terminating @code{(char *)0}
2587(@code{(argz_count (@var{argz}, @var{argz_len}) + 1) * sizeof (char *)}
2588bytes should be enough). Note that the string pointers stored into
2589@var{argv} point into @var{argz}---they are not copies---and so
2590@var{argz} must be copied if it will be changed while @var{argv} is
2591still active. This function is useful for passing the elements in
2592@var{argz} to an exec function (@pxref{Executing a File}).
2593@end deftypefun
2594
5649a1d6
UD
2595@comment argz.h
2596@comment GNU
b13927da 2597@deftypefun {void} argz_stringify (char *@var{argz}, size_t @var{len}, int @var{sep})
11087373 2598@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
b13927da
UD
2599The @code{argz_stringify} converts @var{argz} into a normal string with
2600the elements separated by the character @var{sep}, by replacing each
2601@code{'\0'} inside @var{argz} (except the last one, which terminates the
2602string) with @var{sep}. This is handy for printing @var{argz} in a
2603readable manner.
2604@end deftypefun
2605
5649a1d6
UD
2606@comment argz.h
2607@comment GNU
b13927da 2608@deftypefun {error_t} argz_add (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str})
11087373
AO
2609@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2610@c Calls strlen and argz_append.
b13927da
UD
2611The @code{argz_add} function adds the string @var{str} to the end of the
2612argz vector @code{*@var{argz}}, and updates @code{*@var{argz}} and
2613@code{*@var{argz_len}} accordingly.
2614@end deftypefun
2615
5649a1d6
UD
2616@comment argz.h
2617@comment GNU
b13927da 2618@deftypefun {error_t} argz_add_sep (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str}, int @var{delim})
11087373 2619@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
b13927da 2620The @code{argz_add_sep} function is similar to @code{argz_add}, but
49c091e5 2621@var{str} is split into separate elements in the result at occurrences of
b13927da 2622the character @var{delim}. This is useful, for instance, for
5649a1d6 2623adding the components of a Unix search path to an argz vector, by using
b13927da
UD
2624a value of @code{':'} for @var{delim}.
2625@end deftypefun
2626
5649a1d6
UD
2627@comment argz.h
2628@comment GNU
b13927da 2629@deftypefun {error_t} argz_append (char **@var{argz}, size_t *@var{argz_len}, const char *@var{buf}, size_t @var{buf_len})
11087373 2630@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
b13927da
UD
2631The @code{argz_append} function appends @var{buf_len} bytes starting at
2632@var{buf} to the argz vector @code{*@var{argz}}, reallocating
2633@code{*@var{argz}} to accommodate it, and adding @var{buf_len} to
2634@code{*@var{argz_len}}.
2635@end deftypefun
2636
5649a1d6
UD
2637@comment argz.h
2638@comment GNU
30aa5785 2639@deftypefun {void} argz_delete (char **@var{argz}, size_t *@var{argz_len}, char *@var{entry})
11087373
AO
2640@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2641@c Calls free if no argument is left.
b13927da
UD
2642If @var{entry} points to the beginning of one of the elements in the
2643argz vector @code{*@var{argz}}, the @code{argz_delete} function will
2644remove this entry and reallocate @code{*@var{argz}}, modifying
2645@code{*@var{argz}} and @code{*@var{argz_len}} accordingly. Note that as
2646destructive argz functions usually reallocate their argz argument,
2647pointers into argz vectors such as @var{entry} will then become invalid.
2648@end deftypefun
2649
5649a1d6
UD
2650@comment argz.h
2651@comment GNU
b13927da 2652@deftypefun {error_t} argz_insert (char **@var{argz}, size_t *@var{argz_len}, char *@var{before}, const char *@var{entry})
11087373
AO
2653@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2654@c Calls argz_add or realloc and memmove.
b13927da
UD
2655The @code{argz_insert} function inserts the string @var{entry} into the
2656argz vector @code{*@var{argz}} at a point just before the existing
2657element pointed to by @var{before}, reallocating @code{*@var{argz}} and
2658updating @code{*@var{argz}} and @code{*@var{argz_len}}. If @var{before}
2659is @code{0}, @var{entry} is added to the end instead (as if by
2660@code{argz_add}). Since the first element is in fact the same as
2661@code{*@var{argz}}, passing in @code{*@var{argz}} as the value of
2662@var{before} will result in @var{entry} being inserted at the beginning.
2663@end deftypefun
2664
5649a1d6
UD
2665@comment argz.h
2666@comment GNU
8ded91fb 2667@deftypefun {char *} argz_next (const char *@var{argz}, size_t @var{argz_len}, const char *@var{entry})
11087373 2668@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
b13927da
UD
2669The @code{argz_next} function provides a convenient way of iterating
2670over the elements in the argz vector @var{argz}. It returns a pointer
2671to the next element in @var{argz} after the element @var{entry}, or
2672@code{0} if there are no elements following @var{entry}. If @var{entry}
2673is @code{0}, the first element of @var{argz} is returned.
2674
2675This behavior suggests two styles of iteration:
2676
2677@smallexample
2678 char *entry = 0;
2679 while ((entry = argz_next (@var{argz}, @var{argz_len}, entry)))
2680 @var{action};
2681@end smallexample
2682
2683(the double parentheses are necessary to make some C compilers shut up
2684about what they consider a questionable @code{while}-test) and:
2685
2686@smallexample
2687 char *entry;
2688 for (entry = @var{argz};
2689 entry;
2690 entry = argz_next (@var{argz}, @var{argz_len}, entry))
2691 @var{action};
2692@end smallexample
2693
2694Note that the latter depends on @var{argz} having a value of @code{0} if
2695it is empty (rather than a pointer to an empty block of memory); this
2696invariant is maintained for argz vectors created by the functions here.
2697@end deftypefun
2698
d705269e
UD
2699@comment argz.h
2700@comment GNU
2701@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}})
11087373 2702@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
49c091e5 2703Replace any occurrences of the string @var{str} in @var{argz} with
d705269e
UD
2704@var{with}, reallocating @var{argz} as necessary. If
2705@var{replace_count} is non-zero, @code{*@var{replace_count}} will be
2706incremented by number of replacements performed.
2707@end deftypefun
2708
b13927da
UD
2709@node Envz Functions, , Argz Functions, Argz and Envz Vectors
2710@subsection Envz Functions
2711
2712Envz vectors are just argz vectors with additional constraints on the form
2713of each element; as such, argz functions can also be used on them, where it
2714makes sense.
2715
2716Each element in an envz vector is a name-value pair, separated by a @code{'='}
2717character; if multiple @code{'='} characters are present in an element, those
2718after the first are considered part of the value, and treated like all other
2719non-@code{'\0'} characters.
2720
2721If @emph{no} @code{'='} characters are present in an element, that element is
2722considered the name of a ``null'' entry, as distinct from an entry with an
2723empty value: @code{envz_get} will return @code{0} if given the name of null
2724entry, whereas an entry with an empty value would result in a value of
2725@code{""}; @code{envz_entry} will still find such entries, however. Null
2726entries can be removed with @code{envz_strip} function.
2727
2728As with argz functions, envz functions that may allocate memory (and thus
2729fail) have a return type of @code{error_t}, and return either @code{0} or
2730@code{ENOMEM}.
2731
2732@pindex envz.h
2733These functions are declared in the standard include file @file{envz.h}.
2734
5649a1d6
UD
2735@comment envz.h
2736@comment GNU
b13927da 2737@deftypefun {char *} envz_entry (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
11087373 2738@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
b13927da
UD
2739The @code{envz_entry} function finds the entry in @var{envz} with the name
2740@var{name}, and returns a pointer to the whole entry---that is, the argz
2741element which begins with @var{name} followed by a @code{'='} character. If
2742there is no entry with that name, @code{0} is returned.
2743@end deftypefun
2744
5649a1d6
UD
2745@comment envz.h
2746@comment GNU
b13927da 2747@deftypefun {char *} envz_get (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
11087373 2748@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
b13927da
UD
2749The @code{envz_get} function finds the entry in @var{envz} with the name
2750@var{name} (like @code{envz_entry}), and returns a pointer to the value
2751portion of that entry (following the @code{'='}). If there is no entry with
2752that name (or only a null entry), @code{0} is returned.
2753@end deftypefun
2754
5649a1d6
UD
2755@comment envz.h
2756@comment GNU
b13927da 2757@deftypefun {error_t} envz_add (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name}, const char *@var{value})
11087373
AO
2758@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2759@c Calls envz_remove, which calls enz_entry and argz_delete, and then
2760@c argz_add or equivalent code that reallocs and appends name=value.
b13927da
UD
2761The @code{envz_add} function adds an entry to @code{*@var{envz}}
2762(updating @code{*@var{envz}} and @code{*@var{envz_len}}) with the name
2763@var{name}, and value @var{value}. If an entry with the same name
2764already exists in @var{envz}, it is removed first. If @var{value} is
2765@code{0}, then the new entry will the special null type of entry
2766(mentioned above).
2767@end deftypefun
2768
5649a1d6
UD
2769@comment envz.h
2770@comment GNU
b13927da 2771@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})
11087373 2772@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
b13927da
UD
2773The @code{envz_merge} function adds each entry in @var{envz2} to @var{envz},
2774as if with @code{envz_add}, updating @code{*@var{envz}} and
2775@code{*@var{envz_len}}. If @var{override} is true, then values in @var{envz2}
2776will supersede those with the same name in @var{envz}, otherwise not.
2777
2778Null entries are treated just like other entries in this respect, so a null
2779entry in @var{envz} can prevent an entry of the same name in @var{envz2} from
2780being added to @var{envz}, if @var{override} is false.
2781@end deftypefun
2782
5649a1d6
UD
2783@comment envz.h
2784@comment GNU
b13927da 2785@deftypefun {void} envz_strip (char **@var{envz}, size_t *@var{envz_len})
11087373 2786@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
b13927da
UD
2787The @code{envz_strip} function removes any null entries from @var{envz},
2788updating @code{*@var{envz}} and @code{*@var{envz_len}}.
2789@end deftypefun
11087373
AO
2790
2791@c FIXME this are undocumented:
2792@c strcasecmp_l @safety{@mtsafe{}@assafe{}@acsafe{}} see strcasecmp