Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
  2. #include <libc/stubs.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <libc/unconst.h>
  7.  
  8. int opterr = 1, optind = 1, optopt = 0;
  9. char *optarg = 0;
  10.  
  11. #define BADCH   (int)'?'
  12. #define EMSG    ""
  13.  
  14. int
  15. getopt(int nargc, char *const nargv[], const char *ostr)
  16. {
  17.   static const char *place = EMSG;      /* option letter processing */
  18.   char *oli;                    /* option letter list index */
  19.   char *p;
  20.  
  21.   if (!*place)
  22.   {
  23.     if (optind >= nargc || *(place = nargv[optind]) != '-')
  24.     {
  25.       place = EMSG;
  26.       return(EOF);
  27.     }
  28.     if (place[1] && *++place == '-')
  29.     {
  30.       ++optind;
  31.       place = EMSG;
  32.       return(EOF);
  33.     }
  34.   }
  35.  
  36.   if ((optopt = (int)*place++) == (int)':'
  37.       || !(oli = strchr(ostr, optopt)))
  38.   {
  39.     /*
  40.      * if the user didn't specify '-' as an option,
  41.      * assume it means EOF.
  42.      */
  43.     if (optopt == (int)'-')
  44.       return EOF;
  45.     if (!*place)
  46.       ++optind;
  47.     if (opterr)
  48.     {
  49.       if (!(p = strrchr(*nargv, '/')))
  50.         p = *nargv;
  51.       else
  52.         ++p;
  53.       fprintf(stderr, "%s: illegal option -- %c\n", p, optopt);
  54.     }
  55.     return BADCH;
  56.   }
  57.   if (*++oli != ':')
  58.   {             /* don't need argument */
  59.     optarg = NULL;
  60.     if (!*place)
  61.       ++optind;
  62.   }
  63.   else
  64.   {                             /* need an argument */
  65.     if (*place)                 /* no white space */
  66.       optarg = unconst(place, char *);
  67.     else if (nargc <= ++optind)
  68.     { /* no arg */
  69.       place = EMSG;
  70.       if (!(p = strrchr(*nargv, '/')))
  71.         p = *nargv;
  72.       else
  73.         ++p;
  74.       if (opterr)
  75.         fprintf(stderr, "%s: option requires an argument -- %c\n",
  76.                 p, optopt);
  77.       return BADCH;
  78.     }
  79.     else                        /* white space */
  80.       optarg = nargv[optind];
  81.     place = EMSG;
  82.     ++optind;
  83.   }
  84.   return optopt;                /* dump back option letter */
  85. }
  86.