home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume26 / utree / part01 / sup / getopt.c next >
Encoding:
C/C++ Source or Header  |  1992-09-06  |  1.9 KB  |  77 lines

  1. /*
  2.  *      GETOPT.C
  3.  *      System V like command line option parser
  4.  */
  5.  
  6. /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
  7. /* !  This function is a modified version of getopt() `stolen' from   ! */
  8. /* !  the public domain electronic mail system ELM version 2.3        ! */
  9. /* !    (C) Copyright 1986, 1987, by Dave Taylor                      ! */
  10. /* !    (C) Copyright 1988, 1989, 1990, USENET Community Trust        ! */
  11. /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
  12.  
  13. #include <stdio.h>
  14.  
  15. #ifdef  SYSV
  16. #define index(s, c)  strchr(s, c)
  17. extern char *strchr();
  18. #else
  19. extern char *index();
  20. #endif
  21.  
  22. int  opterr = 1;                /* Error handling flag  */
  23. int  optind = 1;                /* Index in argv        */
  24. int  optopt;                    /* Current option       */
  25. char *optarg;                   /* Option argument      */
  26.  
  27. getopt(argc, argv, opts)
  28.   register int argc;
  29.   register char **argv, *opts;
  30. {
  31.   static int sp = 1;
  32.   register char *cp;
  33.   register int c;
  34.  
  35.   if(sp == 1)
  36.     if(optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
  37.       return(EOF);
  38.     else if( !strcmp(argv[optind], "--")) {
  39.       optind++;
  40.       return(EOF);
  41.     }
  42.   optopt = c = argv[optind][sp];
  43.   if(c == ':' || (cp = index(opts, c)) == NULL) {
  44.     if(opterr)
  45.       (void) fprintf(stderr, "%s: illegal option -- %c\n", argv[0], c);
  46.     else if(argv[optind][++sp] == '\0') {
  47.       optind++;
  48.       sp = 1;
  49.     }
  50.     return('?');
  51.   }
  52.   if(*++cp == ':') {
  53.     if(argv[optind][sp+1] != '\0')
  54.       optarg = &argv[optind++][sp+1];
  55.     else if(++optind >= argc) {
  56.       if(opterr)
  57.        (void) fprintf(stderr, "%s: option requires an argument -- %c\n",
  58.                       argv[0], c);
  59.       sp = 1;
  60.       return('?');
  61.     }
  62.     else
  63.       optarg = argv[optind++];
  64.     sp = 1;
  65.   }
  66.   else {
  67.     if(argv[optind][++sp] == '\0') {
  68.       sp = 1;
  69.       optind++;
  70.     }
  71.     optarg = NULL;
  72.   }
  73.   return(c);
  74.  
  75. } /* getopt() */
  76.  
  77.