1 .\" $OpenBSD: strtonum.3,v 1.5 2004/05/06 06:19:01 tedu Exp $
2 .\" $DragonFly: src/lib/libc/stdlib/strtonum.3,v 1.1 2004/08/15 16:01:11 joerg Exp $
4 .\" Copyright (c) 2004 Ted Unangst
6 .\" Permission to use, copy, modify, and distribute this software for any
7 .\" purpose with or without fee is hereby granted, provided that the above
8 .\" copyright notice and this permission notice appear in all copies.
10 .\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 .\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 .\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 .\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 .\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 .Nd "reliably convert string value to an integer"
25 .Fd #include <stdlib.h>
26 .Fd #include <limits.h>
27 .Ft unsigned long long
29 .Fa "const char *nptr"
30 .Fa "long long minval"
31 .Fa "unsigned long long maxval"
32 .Fa "const char **errstr"
37 function converts the string in
40 .Li unsigned long long
42 Negative values may be obtained by casting the result.
45 function was designed to facilitate safe, robust programming
46 and overcome the shortcomings of the
52 The string may begin with an arbitrary amount of whitespace
55 followed by a single optional
61 The remainder of the string is converted to an
62 .Li unsigned long long
63 value according to base 10.
65 The value obtained is then checked against the provided
74 stores an error string in
76 indicating the failure.
80 function returns the result of the conversion,
81 unless the value would exceed the provided bounds or is invalid.
82 On error, 0 is returned and
84 will point to an error message.
88 correctly is meant to be simpler than the alternative functions.
89 .Bd -literal -offset indent
93 iterations = strtonum(optarg, 1, 64, &errstr);
95 errx(1, "number of iterations is %s: %s", errstr, optarg);
98 The above example will guarantee that the value of iterations is between
103 The given string was out of range.
105 The given string did not consist solely of digit characters.
108 If an error occurs, errstr will be set to one of the following strings.
109 .Bl -tag -width "too large"
111 The result was larger than the provided maximum value.
113 The result was smaller than the provided minimum value.
115 The string did not consist solely of digit characters.
128 was originally implemented as an extension on
131 The existing alternatives, such as
135 are either impossible or difficult to use safely.