home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / o / orbits / !orbits / c / getopt next >
Encoding:
Text File  |  1990-11-08  |  2.0 KB  |  60 lines

  1. /*->c.getopt */
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7.  
  8. char *index(char *string,char byte)     /* string index utility */
  9. {
  10.    return(strchr(string,byte));
  11. }
  12.  
  13.  
  14. /*
  15.  * get option letter from argument vector
  16.  */
  17. int    opterr = 1,             /* useless, never set or used */
  18.        optind = 1,             /* index into parent argv vector */
  19.        optopt;                 /* character checked for validity */
  20. char   *optarg;                /* argument associated with option */
  21.  
  22. #define BADCH  (int)'?'
  23. #define EMSG   ""
  24. #define tell(s)        fputs(*nargv,stderr);fputs(s,stderr); \
  25.                fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);
  26.  
  27. int getopt(int nargc,char **nargv,char *ostr)
  28.  
  29. {
  30.        static char     *place = EMSG;  /* option letter processing */
  31.        register char   *oli;           /* option letter list index */
  32.  
  33.        if(!*place) {                   /* update scanning pointer */
  34.                if(optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) return(EOF);
  35.                if (*place == '-') {    /* found "--" */
  36.                        ++optind;
  37.                        return(EOF);
  38.                }
  39.        }                               /* option letter okay? */
  40.        if ((optopt = (int)*place++) == (int)':' || !(oli = index(ostr,optopt))) {
  41.                if(!*place) ++optind;
  42.                tell(": illegal option -- ");
  43.        }
  44.        if (*++oli != ':') {            /* don't need argument */
  45.                optarg = NULL;
  46.                if (!*place) ++optind;
  47.        }
  48.        else {                          /* need an argument */
  49.                if (*place) optarg = place;     /* no white space */
  50.                else if (nargc <= ++optind) {   /* no arg */
  51.                        place = EMSG;
  52.                        tell(": option requires an argument -- ");
  53.                }
  54.                else optarg = nargv[optind];    /* white space */
  55.                place = EMSG;
  56.                ++optind;
  57.        }
  58.        return(optopt);                 /* dump back option letter */
  59. }
  60.