Advertisement
rfmonk

get_num.c

Dec 26th, 2013
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.40 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <limits.h>
  5. #include <errno.h>
  6. #include "get_num.h"
  7.  
  8. static void
  9. gnFail(const char *fname, const char *msg, const char *arg, const char *name)
  10. {
  11.     fprintf(stderr, "%s error", fname);
  12.     if (name != NULL)
  13.         fprintf(stderr, " (in %s)", name);
  14.     fprintf(stderr, ": %s\n", msg);
  15.     if (arg != NULL && *arg != '\0')
  16.         fprintf(stderr, "        offending text: %s\n", arg);
  17.  
  18.     exit(EXIT_FAILURE);
  19.  
  20. }
  21.  
  22. static long
  23. getNum(const char *fname, const char *arg, int flags, const char *name)
  24. {
  25.     long res;
  26.     char *endptr;
  27.     int base;
  28.  
  29.     if (arg == NULL || *arg == '\0')
  30.         gnFail(fname, "null or empty string", arg, name);
  31.  
  32.     base = (flags & GN_ANY_BASE) ? 0 : (flags & GN_BASE_8) ? 8 :
  33.                         (flags & GN_BASE_16) ? 16 : 10;
  34.  
  35.     errno = 0;
  36.     res = strtol(arg, &endptr, base);
  37.     if (errno != 0)
  38.         gnFail(fname, "strtol() failed", arg, name);
  39.     if ((flags & GN_NONNEG) && res < 0)
  40.         gnFail(fname, "value must be > 0", arg, name);
  41.  
  42.     return res;
  43.  
  44. }
  45.  
  46. long
  47. getLong(const char *arg, int flags, const char *name)
  48. {
  49.     return getNum("getLong", arg, flags, name);
  50. }
  51.  
  52. int
  53. getInt(const char *arg, int flags, const char *name)
  54.  
  55.     long res;
  56.  
  57.     res = getNum("getInt", arg, flags, name);
  58.  
  59.     if (res > INT_MAX || res < INT_MIN)
  60.         gnFail("getInt", "integer out of range", arg, name);
  61.  
  62.         return (int) res;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement