From: W. Trevor King Date: Wed, 23 Jan 2013 19:59:03 +0000 (-0500) Subject: safe-strto.c: Add safe_strtol and generalize the library name X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=2a86b4f845e043f8193ef0589ea23d5c4a386936;p=assignment-template.git safe-strto.c: Add safe_strtol and generalize the library name Also fix masking defines to match the library name's pattern. --- diff --git a/safe-strtod.c b/safe-strto.c similarity index 68% rename from safe-strtod.c rename to safe-strto.c index 8396a0e..6a63dbe 100644 --- a/safe-strtod.c +++ b/safe-strto.c @@ -1,5 +1,5 @@ /* -Safe string-to-double conversion +Safe string-to-* conversion Copyright (C) 2013 W. Trevor King @@ -20,7 +20,27 @@ along with this program. If not, see . #include /* for strtod(), exit(), EXIT_* */ #include /* for stderr, *printf(), perror() */ #include /* for errno */ -#include "safe-strtod.h" /* check safe_strtod() declaration */ +#include "safe-strto.h" /* check safe_strto*() declarations */ + +long int safe_strtol(const char *str, int base, const char *name) +{ + char *endptr; + long int x = strtol(str, &endptr, base); + + if (errno) { + fprintf(stderr, "error converting %s to a long integer for %s:\n", + str, name); + perror("strtol"); + exit(EXIT_FAILURE); + } + if (endptr[0] != '\0') { + fprintf(stderr, "error converting %s to a long integer for %s:\n", + str, name); + fprintf(stderr, "leftover characters: %s\n", endptr); + exit(EXIT_FAILURE); + } + return x; +} double safe_strtod(const char *str, const char *name) { diff --git a/safe-strtod.h b/safe-strto.h similarity index 80% rename from safe-strtod.h rename to safe-strto.h index e50a9c3..e163843 100644 --- a/safe-strtod.h +++ b/safe-strto.h @@ -1,5 +1,5 @@ /* -Safe string-to-double conversion +Safe string-to-* conversion Copyright (C) 2013 W. Trevor King @@ -17,9 +17,10 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ -#ifndef _STRTOD_SAFE_H_ -#define _STRTOD_SAFE_H_ +#ifndef _SAFE_STRTO_H_ +#define _SAFE_STRTO_H_ +long int safe_strtol(const char *str, int base, const char *name); double safe_strtod(const char *str, const char *name); -#endif /* _STRTOD_SAFE_H_ */ +#endif /* _SAFE_STRTO_H_ */