home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / X / mit / demos / maze / getopt.c next >
Encoding:
C/C++ Source or Header  |  1991-02-18  |  1.3 KB  |  69 lines

  1. /*
  2. **  GETOPT PROGRAM AND LIBRARY ROUTINE
  3. **
  4. **  I wrote main() and AT&T wrote getopt() and we both put our efforts into
  5. **  the public domain via mod.sources.
  6. **    Rich $alz
  7. **    Mirror Systems
  8. **    (mirror!rs, rs@mirror.TMC.COM)
  9. **    August 10, 1986
  10. ** 
  11. **  This is the public-domain AT&T getopt(3) code.  Hacked by Rich and by Jim.
  12. */
  13.  
  14. #include <stdio.h>
  15. #include <X11/Xos.h>
  16.  
  17. #define ERR(_s, _c) { if (opterr) fprintf (stderr, "%s%s%c\n", argv[0], _s, _c);}
  18.  
  19. int    opterr = 1;
  20. int    optind = 1;
  21. int    optopt;
  22. char    *optarg;
  23.  
  24. int
  25. getopt(argc, argv, opts)
  26. int    argc;
  27. char    **argv, *opts;
  28. {
  29.     static int sp = 1;
  30.     register int c;
  31.     register char *cp;
  32.  
  33.     if(sp == 1)
  34.         if(optind >= argc ||
  35.            argv[optind][0] != '-' || argv[optind][1] == '\0')
  36.             return(EOF);
  37.         else if(strcmp(argv[optind], "--") == NULL) {
  38.             optind++;
  39.             return(EOF);
  40.         }
  41.     optopt = c = argv[optind][sp];
  42.     if(c == ':' || (cp=index(opts, c)) == NULL) {
  43.         ERR(": illegal option -- ", c);
  44.         if(argv[optind][++sp] == '\0') {
  45.             optind++;
  46.             sp = 1;
  47.         }
  48.         return('?');
  49.     }
  50.     if(*++cp == ':') {
  51.         if(argv[optind][sp+1] != '\0')
  52.             optarg = &argv[optind++][sp+1];
  53.         else if(++optind >= argc) {
  54.             ERR(": option requires an argument -- ", c);
  55.             sp = 1;
  56.             return('?');
  57.         } else
  58.             optarg = argv[optind++];
  59.         sp = 1;
  60.     } else {
  61.         if(argv[optind][++sp] == '\0') {
  62.             sp = 1;
  63.             optind++;
  64.         }
  65.         optarg = NULL;
  66.     }
  67.     return(c);
  68. }
  69.