|
|
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: ! 60: return(c); ! 61: } ! 62: ! 63: #ifdef TEST ! 64: /* ! 65: * This test example shows how to use getargs in a program. ! 66: * Typical test lines are ! 67: * getargs -fxxx -f yyy a b c -x -gabc -g ! 68: * getargs -xj # invalid stuff ! 69: */ ! 70: main(argc, argv) ! 71: char *argv[]; ! 72: { ! 73: char c; ! 74: ! 75: while(EOF != (c = getargs(argc, argv, "xyf:g!"))) { ! 76: switch(c) { ! 77: case 'x': ! 78: case 'y': ! 79: printf("option %c\n", c); ! 80: break; ! 81: case 'g': ! 82: if (*optarg) ! 83: printf("option g with %s\n", optarg); ! 84: else ! 85: printf("option g with no argument\n"); ! 86: break; ! 87: case 'f': ! 88: printf("option f with %s\n", optarg); ! 89: break; ! 90: case 0: ! 91: printf("argument '%s'\n", optarg); ! 92: break; ! 93: default: ! 94: printf( ! 95: "usage: getargs [-xy] [-f filen] [-g[option]] name ...\n"); ! 96: exit(1); ! 97: } ! 98: } ! 99: exit(0); ! 100: } ! 101: #endif
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.