home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume4 / fmtr / getopt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1986-11-30  |  1.6 KB  |  61 lines

  1. #ifndef lint
  2. static char rcsid[] = "$Header: getopt.c,v 1.3 86/05/05 14:20:35 root Exp $";
  3. #endif
  4.  
  5. /* got this off net.sources */
  6. #include <stdio.h>
  7.  
  8. /*
  9.  * get option letter from argument vector
  10.  */
  11. int    opterr = 1,    /* if set to zero no message for bad option */
  12.     optind = 1,    /* index into parent argv vector */
  13.     optopt;        /* character checked for validity */
  14. char    *optarg;    /* argument associated with option */
  15.  
  16. #define BADCH    (int)'?'
  17. #define EMSG    ""
  18.  
  19. getopt(nargc,nargv,ostr)
  20. int    nargc;
  21. char    **nargv,
  22.     *ostr;
  23. {
  24.     static char    *place = EMSG;    /* option letter processing */
  25.     register char    *oli;        /* option letter list index */
  26.     char    *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.     if ((optopt = (int)*place++) == (int)':' || !(oli = index(ostr,optopt))) {
  37.     if(!*place) ++optind;
  38.     if (opterr)
  39.         fprintf(stderr, "%s: illegal option -- %c\n", *nargv, optopt);
  40.     return(BADCH);
  41.     }
  42.     if (*++oli != ':') {        /* don't need argument */
  43.     optarg = NULL;
  44.     if (!*place) ++optind;
  45.     }
  46.     else {                /* need an argument */
  47.     if (*place) optarg = place;    /* no white space */
  48.     else if (nargc <= ++optind) {    /* no arg */
  49.         place = EMSG;
  50.         if (opterr)
  51.         fprintf(stderr, "%s: option requires an argument -- %c\n",
  52.             *nargv, optopt);
  53.         return(BADCH);
  54.     }
  55.      else optarg = nargv[optind];    /* white space */
  56.     place = EMSG;
  57.     ++optind;
  58.     }
  59.     return(optopt);            /* dump back option letter */
  60. }
  61.