From: Sami Kerola Date: Sun, 25 Sep 2011 09:03:07 +0000 (+0200) Subject: lib: [strutils] add strtod_or_err() function X-Git-Tag: v2.21-rc1~356^2~9 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=a9f97001c3fc420d1433d253539800cbb4864003;p=thirdparty%2Futil-linux.git lib: [strutils] add strtod_or_err() function Signed-off-by: Sami Kerola --- diff --git a/include/strutils.h b/include/strutils.h index 08ba09c01c..dbcc3d904f 100644 --- a/include/strutils.h +++ b/include/strutils.h @@ -6,6 +6,7 @@ #include extern int strtosize(const char *str, uintmax_t *res); +extern double strtod_or_err(const char *str, const char *errmesg); extern long strtol_or_err(const char *str, const char *errmesg); extern long long strtoll_or_err(const char *str, const char *errmesg); extern unsigned long strtoul_or_err(const char *str, const char *errmesg); diff --git a/lib/strutils.c b/lib/strutils.c index da395e4472..aad9f77381 100644 --- a/lib/strutils.c +++ b/lib/strutils.c @@ -167,6 +167,30 @@ char *strndup(const char *s, size_t n) } #endif +/* + * same as strtod(3) but exit on failure instead of returning crap + */ +double strtod_or_err(const char *str, const char *errmesg) +{ + double num; + char *end = NULL; + + if (str == NULL || *str == '\0') + goto err; + errno = 0; + num = strtod(str, &end); + + if (errno || str == end || (end && *end)) + goto err; + + return num; + err: + if (errno) + err(EXIT_FAILURE, "%s: '%s'", errmesg, str); + else + errx(EXIT_FAILURE, "%s: '%s'", errmesg, str); + return 0; +} /* * same as strtol(3) but exit on failure instead of returning crap */