home *** CD-ROM | disk | FTP | other *** search
/ Simtel MSDOS - Coast to Coast / simteldosarchivecoasttocoast2.iso / calculat / units_am.zip / GETOPT.C next >
C/C++ Source or Header  |  1993-07-02  |  2KB  |  74 lines

  1. /* optarg - parse command-line arguments */
  2. /* Author: AT&T */
  3.  
  4. #include <stdio.h>
  5.  
  6. #define ERR(s, c)                if(opterr){\
  7.     char errbuf[2];\
  8.     errbuf[0] = c; errbuf[1] = '\n';\
  9.     fwrite(argv[0], 1, (unsigned)strlen(argv[0]),stderr);\
  10.     fwrite(s, 1, (unsigned)strlen(s),stderr);\
  11.     fwrite(errbuf, 1, 2, stderr);}
  12.  
  13. extern int strcmp();
  14. extern char *strchr();
  15. extern int strlen();
  16.  
  17. int    opterr = 1;        /* getopt prints errors if this is on */
  18. int    optind = 1;        /* token pointer */
  19. int    optopt;            /* option character passed back to user */
  20. char    *optarg;        /* flag argument (or value) */
  21.  
  22. int    /* return option character, EOF if no more or ? if problem */
  23. getopt(argc, argv, opts)
  24. int    argc;
  25. char    **argv;
  26. char    *opts;                /* option string */
  27. {
  28.     static int sp = 1;        /* character index in current token */
  29.     register char *cp;        /* pointer into current token */
  30.  
  31.     if(sp == 1)
  32.         /* check for more flag-like tokens */
  33.         if(optind >= argc ||
  34.            argv[optind][0] != '-' || argv[optind][1] == '\0')
  35.             return(EOF);
  36.         else if(strcmp(argv[optind], "--") == 0) {
  37.             optind++;
  38.             return(EOF);
  39.         }
  40.     optopt = argv[optind][sp];
  41.     if(optopt == ':' || (cp=strchr(opts, optopt)) == 0) {
  42.         ERR(": illegal option -- ", optopt);
  43.         /* if no chars left in this token, move to next token */
  44.         if(argv[optind][++sp] == '\0') {
  45.             optind++;
  46.             sp = 1;
  47.         }
  48.         return('?');
  49.     }
  50.  
  51.     if(*++cp == ':') {    /* if a value is expected, get it */
  52.         if(argv[optind][sp+1] != '\0')
  53.             /* flag value is rest of current token */
  54.             optarg = &argv[optind++][sp+1];
  55.         else if(++optind >= argc) {
  56.             ERR(": option requires an argument -- ", optopt);
  57.             sp = 1;
  58.             return('?');
  59.         } else
  60.             /* flag value is next token */
  61.             optarg = argv[optind++];
  62.         sp = 1;
  63.     } else {
  64.         /* set up to look at next char in token, next time */
  65.         if(argv[optind][++sp] == '\0') {
  66.             /* no more in current token, so setup next token */
  67.             sp = 1;
  68.             optind++;
  69.         }
  70.         optarg = 0;
  71.     }
  72.     return(optopt);/* return the current flag character found */
  73. }
  74.