STRTOU(3) | Library Functions Manual | STRTOU(3) |
strtou
—
#include <inttypes.h>
uintmax_t
strtou
(const char * restrict
nptr, char ** restrict endptr,
int base, uintmax_t lo,
uintmax_t hi, int *rstatus);
strtou
() function converts the string in
nptr to an uintmax_t value. The
strtou
() function uses internally
strtoumax(3) and ensures that
the result is always in the range [ lo ..
hi ]. In adddition it always places
0
on success or a conversion status in the
rstatus argument, avoiding the
errno
gymnastics the other functions require. The
rstatus argument can be NULL
if
conversion status is to be ignored.
The string may begin with an arbitrary amount of white space (as
determined by isspace(3))
followed by a single optional ‘+
’ or
‘-
’ sign. If
base is zero or 16, the string may then include a
‘0x
’ or
‘0X
’ prefix, and the number will be
read in base 16; otherwise, a zero base is taken as 10
(decimal) unless the next character is
‘0
’, in which case it is taken as 8
(octal).
The remainder of the string is converted to an
uintmax_t value in the obvious manner, stopping at the end
of the string or at the first character that does not produce a valid digit
in the given base. (In bases above 10, the letter
‘A
’ in either upper or lower case
represents 10, ‘B
’ represents 11, and
so forth, with ‘Z
’ representing
35.)
If endptr is non-nil,
strtou
() stores the address of the first invalid
character in *endptr. If there were no digits at all,
however, strtou
() stores the original value of
nptr in *endptr. (Thus, if
*nptr is not
‘\0
’ but
**endptr is ‘\0
’
on return, the entire string was valid.)
strtou
() function always returns the closest value
in the range specified by the lo and
hi arguments.
The errno value is guaranteed to be left unchanged.
Errors are stored as the conversion status in the rstatus argument.
[1..99]
range no matter what the input is, and warn if
the conversion failed.
int e; uintmax_t lval = strtou(buf, NULL, 0, 1, 99, &e); if (e) warnc(e, "conversion of `%s' to a number failed, using %ju", buf, lval);
ECANCELED
]EINVAL
]ENOTSUP
]ERANGE
]strtou
() function is a
NetBSD extension.
strtou
() function first appeared in
NetBSD 7. OpenBSD introduced
the strtonum
(3) function for the
same purpose, but the interface makes it impossible to properly differentiate
illegal returns.
November 13, 2015 | NetBSD 9.0 |