/* loop.c - Copyright (C) 1997 Murray Nesbitt (websrc@nesbitt.ca) This program is protected and licensed under the following terms and conditions: 1) it may not be redistributed in binary form without the explicit permission of the author; 2) when redistributed in source form, in whole or in part, this complete copyright statement must remain intact. */ /* Usage: loop [-o|x] start end [increment] [width] Prints to stdout a series of numbers from `start' to `end', with optional increment and zero-padded field width. Hex (-x) or octal (-o) output formats are available. Negative numbers are allowed, and a negative `increment' does the expected thing. Examples: $ loop 1 3 1 2 3 $ loop 2 6 2 2 4 6 $ loop 2 10 2 2 02 04 06 08 10 $ # Create 10 test files, 'test01' through 'test10' $ for i in `loop 1 10 1 2`; do touch test$i; done $ loop -x -8 8 4 8 FFFFFFF8 FFFFFFFC 00000000 00000004 00000008 $ loop 4 0 -1 4 3 2 1 0 */ #include #include #include /* isalpha() */ /* Format specifier for hex and octal numbers. If you prefer lowercase hex numbers, change 'X' to 'x'. */ #define HEX_CHAR 'X' #define OCTAL_CHAR 'o' /* This needs to be at least long enough to build up a format string of the form "%0[INTMAX]d\n". */ #define FORMATLENGTH 20 void usage(char *prog) { fprintf(stderr, "Usage: %s [-o|x] start end [increment] [width]\n", prog); exit(EXIT_FAILURE); } int main(int argc, char **argv) { char radix_char = 'd'; /* default to decimal output. */ int i = 1; long start, end, padding, increment = 1; char format[FORMATLENGTH], *chr; if (argc < 3) usage(argv[0]); chr = argv[i]; if (*chr++ == '-' && isalpha((int)*chr)) { if ((*chr == 'o' || *chr == 'x') && *(chr + 1) == '\0' && argc > 3) { radix_char = (char)(*chr == 'o' ? OCTAL_CHAR : HEX_CHAR); i++; } else usage(argv[0]); } /* We know these two arguments exist. */ start = atol(argv[i++]); end = atol(argv[i++]); if (argc > i && (increment = atol(argv[i++])) == 0) { usage(argv[0]); } /* Yet another argument. */ if (argc > i) { padding = atol(argv[i]); sprintf(format, "%%0%ldl%c\n", padding, radix_char); } else sprintf(format, "%%l%c\n", radix_char); if (increment > 0) { for (i = start; i <= end; i += increment) { printf(format, i); } } else { for (i = start; i >= end; i += increment) { printf(format, i); } } exit(EXIT_SUCCESS); }