home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / s / sndppr3w.zip / GETOPT.C < prev    next >
C/C++ Source or Header  |  1991-04-26  |  2KB  |  70 lines

  1. /* Getopt.C
  2. ** 4/26/90
  3. ** mjs
  4. **
  5. ** Originally yanked from the MTV raytracer source code, with index()
  6. ** replaced with strchr(), error reporting changed a little bit...
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <string.h>
  11.  
  12. /*
  13.  * get option letter from argument vector
  14.  */
  15. int    opterr = 1,        /* useless, never set or used        */
  16.     optind = 1,        /* index into parent argv vector    */
  17.     optopt;            /* character checked for validity    */
  18. char    *optarg;        /* argument associated with option    */
  19.  
  20. #define BADCH    (int)'?'
  21. #define EMSG    ""
  22. #define err_tell(s)    /* fputs(*nargv,stderr); */ \
  23.         fputc('\n',stderr); \
  24.         fputs(s,stderr); \
  25.         fputc(optopt,stderr); \
  26.         fputc('\n',stderr); \
  27.         return(BADCH);
  28.  
  29. int getopt(int, char *[], char *);    /* function prototype    */
  30. int getopt(int nargc, char *nargv[], char *ostr)
  31. {
  32.     static char    *place = EMSG;    /* option letter processing */
  33.     register char    *oli;        /* option letter list index */
  34.  
  35.     /* allow '-', '/' and '\' as option prefixes    */
  36.     if(!*place) {            /* update scanning pointer */
  37.         if(optind >= nargc || (
  38.            (*(place = nargv[optind]) != '-' ) &&
  39.            (*place != '/' ) && (*place != '\\')) ||
  40.            !*++place) return(EOF);
  41.  
  42.         if (*place == '-') {    /* found "--" */
  43.             ++optind;
  44.             return(EOF);
  45.         }
  46.     }                /* option letter okay? */
  47.     if ((optopt = (int)*place++) == (int)':' ||
  48.         !(oli = strchr(ostr,optopt))) {
  49.         if(!*place) ++optind;
  50.         err_tell("illegal option -- ");
  51.     }
  52.     if (*++oli != ':') {        /* don't need argument */
  53.         optarg = NULL;
  54.         if (!*place) ++optind;
  55.     }
  56.     else {                /* need an argument */
  57.         if (*place) optarg = place;    /* no white space */
  58.         else if (nargc <= ++optind) {    /* no arg */
  59.             place = EMSG;
  60.             err_tell("option requires an argument -- ");
  61.         }
  62.          else optarg = nargv[optind];    /* white space */
  63.         place = EMSG;
  64.         ++optind;
  65.     }
  66.     return(optopt);            /* dump back option letter */
  67. }
  68.  
  69. /*** eof ****************************************************************/
  70.