lib: add strtoul_or_err() function

Signed-off-by: Sami Kerola <kerolasa@iki.fi>
Signed-off-by: Karel Zak <kzak@redhat.com>
This commit is contained in:
Sami Kerola 2011-05-24 22:56:38 +02:00 committed by Karel Zak
parent 8e0ec3b48a
commit e53bc9604c
2 changed files with 25 additions and 0 deletions

View file

@ -8,6 +8,7 @@
extern int strtosize(const char *str, uintmax_t *res);
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);
#ifndef HAVE_STRNLEN
extern size_t strnlen(const char *s, size_t maxlen);

View file

@ -213,6 +213,30 @@ err:
errx(EXIT_FAILURE, "%s: '%s'", errmesg, str);
return 0;
}
/*
* same as strtoul(3) but exit on failure instead of returning crap
*/
unsigned long strtoul_or_err(const char *str, const char *errmesg)
{
unsigned long num;
char *end = NULL;
if (str == NULL || *str == '\0')
goto err;
errno = 0;
num = strtoul(str, &end, 10);
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;
}
/*
* Converts stat->st_mode to ls(1)-like mode string. The size of "str" must