parse_blocksize.c 946 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /*
  2. * Parse a string block size specification. This is approximately a
  3. * subset of the block size specs supported by GNU fileutils:
  4. * "nk" = n kilobytes
  5. * "nM" = n megabytes
  6. * "nG" = n gigabytes
  7. * All numbers are decimal, and suffixes refer to powers of two.
  8. * Case-insensitive.
  9. */
  10. #include <ctype.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #include "defs.h"
  14. #include "misc.h"
  15. unsigned long parse_blocksize(const char *bs)
  16. {
  17. char *suf;
  18. unsigned long r = strtoul(bs, &suf, 10);
  19. if (*suf != '\0') {
  20. while (*suf && isspace((unsigned char)*suf)) suf++;
  21. switch (*suf) {
  22. case 'k': case 'K':
  23. r *= 1024ul;
  24. break;
  25. case 'm': case 'M':
  26. r *= 1024ul * 1024ul;
  27. break;
  28. case 'g': case 'G':
  29. r *= 1024ul * 1024ul * 1024ul;
  30. break;
  31. case '\0':
  32. default:
  33. break;
  34. }
  35. }
  36. return r;
  37. }