|
|
1.1 ! root 1: /* ! 2: * getargs - get option letters and arguments from argv ! 3: * ! 4: * This is an improved form of getopt. If an option is followed ! 5: * by an ! it has an optional argument. ! 6: * while(EOF != (c = getargs(argc, argv, "xyf:g!"))) ! 7: * Is a call of getargs from its test section. The x and y ! 8: * options take no arguments. The f option takes a mandidory ! 9: * argument, -f arg, and -farg, are both legal forms. The g option ! 10: * takes an optional argument which if present must be connected ! 11: * -garg. Additional arguments are returned as if they were preceeded ! 12: * by an option of '\0'. This allows programs such as ld and as to ! 13: * process mixed options and file names. ! 14: */ ! 15: #include <stdio.h> ! 16: ! 17: char *optarg; /* Global argument pointer. */ ! 18: int optix = 1; /* Global argv index. Reset to 1 to rescan. */ ! 19: ! 20: static char *scan = NULL; /* Private scan pointer. */ ! 21: extern char *strchr(); ! 22: ! 23: int ! 24: getargs(argc, argv, optstring) ! 25: int argc; ! 26: char *argv[]; ! 27: char *optstring; ! 28: { ! 29: register char c, a; ! 30: register char *place; ! 31: ! 32: for (optarg = NULL; scan == NULL || !*scan; scan++, optix++) { ! 33: if (optix >= argc) { ! 34: scan = NULL; ! 35: return(EOF); ! 36: } ! 37: if (*(scan = argv[optix]) != '-') { ! 38: optarg = scan; ! 39: scan = NULL; ! 40: optix++; ! 41: return (0); ! 42: } ! 43: } ! 44: ! 45: if ((place = strchr(optstring, c = *scan++)) == NULL || ! 46: c == ':' || c == '!') ! 47: fatal("unknown command option %c", c); ! 48: ! 49: if (((a = place[1]) == ':') || (a == '!')) { ! 50: if (*scan || (a == '!')) { ! 51: optarg = scan; ! 52: scan = NULL; ! 53: } else if (optix < argc) ! 54: optarg = argv[optix++]; ! 55: else ! 56: fatal("command option %c missing its argument", c); ! 57: } ! 58: ! 59: return(c); ! 60: } ! 61: ! 62: #ifdef TEST ! 63: /* ! 64: * This test example shows how to use getargs in a program. ! 65: * Typical test lines are ! 66: * getargs -fxxx -f yyy a b c -x -gabc -g ! 67: * getargs -xj # invalid stuff ! 68: */ ! 69: main(argc, argv) ! 70: char *argv[]; ! 71: { ! 72: char c; ! 73: ! 74: while(EOF != (c = getargs(argc, argv, "xyf:g!"))) { ! 75: switch(c) { ! 76: case 'x': ! 77: case 'y': ! 78: printf("option %c\n", c); ! 79: break; ! 80: case 'g': ! 81: if (*optarg) ! 82: printf("option g with %s\n", optarg); ! 83: else ! 84: printf("option g with no argument\n"); ! 85: break; ! 86: case 'f': ! 87: printf("option f with %s\n", optarg); ! 88: break; ! 89: case 0: ! 90: printf("argument '%s'\n", optarg); ! 91: break; ! 92: default: ! 93: printf( ! 94: "usage: getargs [-xy] [-f filen] [-g[option]] name ...\n"); ! 95: exit(1); ! 96: } ! 97: } ! 98: exit(0); ! 99: } ! 100: #endif
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.