bring in EXAMPLES from OpenBSD.

This commit is contained in:
yamt 2002-08-11 06:53:39 +00:00
parent 22c90da7f0
commit 6410ff3c05

View File

@ -1,4 +1,4 @@
.\" $NetBSD: strtol.3,v 1.17 2002/02/07 07:00:30 ross Exp $
.\" $NetBSD: strtol.3,v 1.18 2002/08/11 06:53:39 yamt Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
@ -37,7 +37,7 @@
.\"
.\" from: @(#)strtol.3 8.1 (Berkeley) 6/4/93
.\"
.Dd April 26, 2001
.Dd August 11, 2002
.Dt STRTOL 3
.Os
.Sh NAME
@ -190,6 +190,68 @@ In these cases,
.Va errno
is set to
.Er ERANGE .
.Sh EXAMPLES
Ensuring that a string is a valid number (i.e., in range and containing no
trailing characters) requires clearing
.Va errno
beforehand explicitly since
.Va errno
is not changed on a successful call to
.Fn strtol ,
and the return value of
.Fn strtol
cannot be used unambiguously to signal an error:
.Bd -literal -offset indent
char *ep;
long lval;
\&...
errno = 0;
lval = strtol(buf, &ep, 10);
if (buf[0] == '\e0' || *ep != '\e0')
goto not_a_number;
if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
goto out_of_range;
.Ed
.Pp
This example will accept
.Dq 12
but not
.Dq 12foo
or
.Dq 12\en .
If trailing whitespace is acceptable, further checks must be done on
.Va *ep ;
alternately, use
.Xr sscanf 3 .
.Pp
If
.Fn strtol
is being used instead of
.Xr atoi 3 ,
error checking is further complicated because the desired return value is an
.Li int
rather than a
.Li long ;
however, on some architectures integers and long integers are the same size.
Thus the following is necessary:
.Bd -literal -offset indent
char *ep;
int ival;
long lval;
\&...
errno = 0;
lval = strtol(buf, &ep, 10);
if (buf[0] == '\e0' || *ep != '\e0')
goto not_a_number;
if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
(lval > INT_MAX || lval < INT_MIN))
goto out_of_range;
ival = lval;
.Ed
.Sh ERRORS
.Bl -tag -width Er
.It Bq Er ERANGE