lib: add strtod_or_err()

Signed-off-by: Sami Kerola <kerolasa@iki.fi>
This commit is contained in:
Sami Kerola 2011-12-18 15:52:57 +01:00
parent 2c8b3a7857
commit c0e7e96c1a
2 changed files with 25 additions and 0 deletions

View File

@ -6,5 +6,6 @@
#define PROCPS_NG_STRUTILS
extern long strtol_or_err(const char *str, const char *errmesg);
extern double strtod_or_err(const char *str, const char *errmesg);
#endif

View File

@ -29,6 +29,30 @@ long strtol_or_err(const char *str, const char *errmesg)
else
errx(EXIT_FAILURE, "%s: '%s'", errmesg, str);
}
/*
* 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;
}
#ifdef TEST_PROGRAM
int main(int argc, char *argv[])