home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: Product / Product.zip / sc621_3.zip / src / getopt.c < prev    next >
C/C++ Source or Header  |  1994-03-15  |  2KB  |  64 lines

  1. /*
  2.  * getopt - get option letter from argv
  3.  *      This software is in the public domain
  4.  *      Originally written by Henry Spencer at the U. of Toronto
  5.  */
  6.  
  7. #include <stdio.h>
  8. #include <string.h>
  9.  
  10. char    *optarg;        /* Global argument pointer. */
  11. int     optind = 0;     /* Global argv index. */
  12.  
  13. static char     *scan = NULL;   /* Private scan pointer. */
  14.  
  15. /* extern char     *index();  obsolete, used strchr (JDC). */
  16.  
  17. int
  18. getopt(argc, argv, optstring)
  19. int argc;
  20. char *argv[];
  21. char *optstring;
  22. {
  23.         register char c;
  24.         register char *place;
  25.  
  26.         optarg = NULL;
  27.  
  28.         if (scan == NULL || *scan == '\0') {
  29.                 if (optind == 0)
  30.                         optind++;
  31.  
  32.                 if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
  33.                         return(EOF);
  34.                 if (strcmp(argv[optind], "--")==0) {
  35.                         optind++;
  36.                         return(EOF);
  37.                 }
  38.  
  39.                 scan = argv[optind]+1;
  40.                 optind++;
  41.         }
  42.  
  43.         c = *scan++;
  44.         place = strchr(optstring, c);
  45.  
  46.         if (place == NULL || c == ':') {
  47.                 fprintf(stderr, "%s: unknown option -%c\n", argv[0], c);
  48.                 return('?');
  49.         }
  50.  
  51.         place++;
  52.         if (*place == ':') {
  53.                 if (*scan != '\0') {
  54.                         optarg = scan;
  55.                         scan = NULL;
  56.                 } else {
  57.                         optarg = argv[optind];
  58.                         optind++;
  59.                 }
  60.         }
  61.  
  62.         return(c);
  63. }
  64.