diff options
author | Sami Kerola | 2011-09-25 11:03:07 +0200 |
---|---|---|
committer | Sami Kerola | 2011-09-29 22:45:27 +0200 |
commit | a9f97001c3fc420d1433d253539800cbb4864003 (patch) | |
tree | f45e30be413e06b1b7d9c48a7f65813442d6e9e1 | |
parent | flock: use strutils.h to check numeric user input (diff) | |
download | kernel-qcow2-util-linux-a9f97001c3fc420d1433d253539800cbb4864003.tar.gz kernel-qcow2-util-linux-a9f97001c3fc420d1433d253539800cbb4864003.tar.xz kernel-qcow2-util-linux-a9f97001c3fc420d1433d253539800cbb4864003.zip |
lib: [strutils] add strtod_or_err() function
Signed-off-by: Sami Kerola <kerolasa@iki.fi>
-rw-r--r-- | include/strutils.h | 1 | ||||
-rw-r--r-- | lib/strutils.c | 24 |
2 files changed, 25 insertions, 0 deletions
diff --git a/include/strutils.h b/include/strutils.h index 08ba09c01..dbcc3d904 100644 --- a/include/strutils.h +++ b/include/strutils.h @@ -6,6 +6,7 @@ #include <sys/types.h> 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 da395e447..aad9f7738 100644 --- a/lib/strutils.c +++ b/lib/strutils.c @@ -168,6 +168,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 */ long strtol_or_err(const char *str, const char *errmesg) |