home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume6 / tif2ps / part02 / getopt.c next >
C/C++ Source or Header  |  1989-02-03  |  2KB  |  62 lines

  1. /*
  2.  *    I got this off net.sources from Henry Spencer.
  3.  *    It is a public domain getopt(3) like in System V.
  4.  *
  5.  *    I made some minor modifications while porting it to MS-DOS.
  6.  *        andy@coma
  7.  */
  8. #include <stdio.h>
  9. #include <string.h>
  10.  
  11. #define    ARGCH    (int)':'
  12. #define BADCH     (int)'?'
  13. #define EMSG     ""
  14. #define    ENDARGS  "--"
  15.  
  16. /*
  17.  * get option letter from argument vector
  18.  */
  19. int    optind = 1,        /* index into parent argv vector */
  20.     optopt;            /* character checked for validity */
  21. char    *optarg;        /* argument associated with option */
  22.  
  23. #define tell(s)    fputs(*nargv,stderr);fputs(s,stderr); \
  24.         (void)fputc(optopt,stderr);(void)fputc('\n',stderr); \
  25.                 return(BADCH);
  26.  
  27. int getopt(nargc,nargv,ostr)
  28. int    nargc;
  29. char    **nargv,
  30.     *ostr;
  31. {
  32.     static char    *place = EMSG;    /* option letter processing */
  33.     register char    *oli;        /* option letter list index */
  34.  
  35.     if(!*place) {            /* update scanning pointer */
  36.         if(optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) return(EOF);
  37.         if (*place == '-') {    /* found "--" */
  38.             ++optind;
  39.             return(EOF);
  40.         }
  41.     }                /* option letter okay? */
  42.     if ((optopt = (int)*place++) == ARGCH || !(oli = strchr (ostr,optopt))) {
  43.         if(!*place) ++optind;
  44.         tell(": illegal option -- ");
  45.     }
  46.     if (*++oli != ARGCH) {        /* don't need argument */
  47.         optarg = NULL;
  48.         if (!*place) ++optind;
  49.     }
  50.     else {                /* need an argument */
  51.         if (*place) optarg = place;    /* no white space */
  52.         else if (nargc <= ++optind) {    /* no arg */
  53.             place = EMSG;
  54.             tell(": option requires an argument -- ");
  55.         }
  56.          else optarg = nargv[optind];    /* white space */
  57.         place = EMSG;
  58.         ++optind;
  59.     }
  60.     return(optopt);            /* dump back option letter */
  61. }
  62.