home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / icon / dos / src / common / getopt.c < prev    next >
C/C++ Source or Header  |  1992-02-10  |  2KB  |  57 lines

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