[PATCH 07/13] lib: add strtoul_or_err() function

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Signed-off-by: Sami Kerola <kerolasa@xxxxxx>
---
 include/strutils.h |    1 +
 lib/strutils.c     |   24 ++++++++++++++++++++++++
 2 files changed, 25 insertions(+), 0 deletions(-)

diff --git a/include/strutils.h b/include/strutils.h
index 99d8acd..f46ccd6 100644
--- a/include/strutils.h
+++ b/include/strutils.h
@@ -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);
diff --git a/lib/strutils.c b/lib/strutils.c
index 21c58da..7dfbdc3 100644
--- a/lib/strutils.c
+++ b/lib/strutils.c
@@ -212,6 +212,30 @@ err:
                errx(EXIT_FAILURE, "%s: '%s'", errmesg, str);
        return 0;
 }
+/*
+ * same as strtoul(3) but exit on failure instead of returning crap
+ */
+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
-- 
1.7.5.2

--
To unsubscribe from this list: send the line "unsubscribe util-linux" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html


[Index of Archives]     [Netdev]     [Ethernet Bridging]     [Linux Wireless]     [Kernel Newbies]     [Security]     [Linux for Hams]     [Netfilter]     [Bugtraq]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux Admin]     [Samba]

  Powered by Linux