home *** CD-ROM | disk | FTP | other *** search
/ ftp.cs.arizona.edu / ftp.cs.arizona.edu.tar / ftp.cs.arizona.edu / icon / historic / v941.tgz / icon.v941src.tar / icon.v941src / src / common / getopt.c < prev    next >
C/C++ Source or Header  |  2001-12-12  |  2KB  |  61 lines

  1. /*
  2.  * getopt.c -- get command-line options.
  3.  */
  4.  
  5. #include "../h/gsupport.h"
  6.  
  7. #ifndef SysOpt
  8. extern char* progname;
  9.  
  10. /*
  11.  * Based on a public domain implementation of System V
  12.  *  getopt(3) by Keith Bostic (keith@seismo), Aug 24, 1984.
  13.  */
  14.  
  15. #define BadCh    (int)'?'
  16. #define EMSG    ""
  17. #define tell(m)    fprintf(stderr,"%s: %s -- %c\n",progname,m,optopt);return BadCh;
  18.  
  19. int optind = 1;        /* index into parent argv vector */
  20. int optopt;        /* character checked for validity */
  21. char *optarg;        /* argument associated with option */
  22.  
  23. int getopt(int nargc, char *const nargv[], const char *ostr)
  24.    {
  25.    static char *place = EMSG;        /* option letter processing */
  26.    register char *oli;            /* option letter list index */
  27.  
  28.    if(!*place) {            /* update scanning pointer */
  29.       if(optind >= nargc || *(place = nargv[optind]) != '-' || !*++place)
  30.          return EOF;
  31.       if (*place == '-') {        /* found "--" */
  32.          ++optind;
  33.          return EOF;
  34.          }
  35.       }                    /* option letter okay? */
  36.  
  37.    if (((optopt=(int)*place++) == (int)':') || (oli=strchr(ostr,optopt)) == 0) {
  38.       if(!*place) ++optind;
  39.       tell("illegal option");
  40.       }
  41.    if (*++oli != ':') {            /* don't need argument */
  42.       optarg = NULL;
  43.       if (!*place) ++optind;
  44.       }
  45.    else {                /* need an argument */
  46.       if (*place) optarg = place;    /* no white space */
  47.       else if (nargc <= ++optind) {    /* no arg */
  48.          place = EMSG;
  49.          tell("option requires an argument");
  50.          }
  51.       else optarg = nargv[optind];    /* white space */
  52.       place = EMSG;
  53.       ++optind;
  54.       }
  55.    return optopt;            /* dump back option letter */
  56.    }
  57.  
  58. #else                    /* SysOpt */
  59. static char junk;            /* prevent empty file */
  60. #endif                    /* SysOpt */
  61.