1 /* safe-atoi.c -- checked string-to-int conversion.
2 Copyright (C) 2007, 2010, 2011 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 /* config.h must be included first. */
31 #include "safe-atoi.h"
35 # define _(Text) gettext (Text)
40 # define N_(String) gettext_noop (String)
42 /* See locate.c for explanation as to why not use (String) */
43 # define N_(String) String
48 safe_atoi (const char *s, enum quoting_style style)
54 lval = strtol (s, &end, 10);
55 if ( (LONG_MAX == lval) || (LONG_MIN == lval) )
57 /* max/min possible value, or an error. */
60 /* too big, or too small. */
61 error (EXIT_FAILURE, errno, "%s", s);
65 /* not a valid number */
66 error (EXIT_FAILURE, errno, "%s", s);
68 /* Otherwise, we do a range chack against INT_MAX and INT_MIN
73 if (lval > INT_MAX || lval < INT_MIN)
75 /* The number was in range for long, but not int. */
77 error (EXIT_FAILURE, errno, "%s", s);
81 error (EXIT_FAILURE, errno, _("Unexpected suffix %s on %s"),
82 quotearg_n_style (0, style, end),
83 quotearg_n_style (1, style, s));
87 error (EXIT_FAILURE, errno, _("Expected an integer: %s"),
88 quotearg_n_style (0, style, s));