home *** CD-ROM | disk | FTP | other *** search
/ Netware Super Library / Netware Super Library.iso / mis_util / trace27 / getopt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-01  |  1.8 KB  |  78 lines

  1. /*
  2.  * getopt - get option letter from argv
  3.  *
  4.  * Called as getopt(argc, argv, optstring ).
  5.  * Optstring is a string of valid option characters. If a character
  6.  * is followed by '':`` then a name can follow.
  7.  * Returns EOF when the scanning has finished or the option when
  8.  * a valid option is found. If an invalid option is found an error
  9.  * is printed in stderr and ''?`` is retured.
  10.  * When scanning is completed the global variable optind is pointing
  11.  * the the next argv (if it exists ).
  12.  * When an option is requested the global character pointer optarg is
  13.  * pointing to it. If no filename was given it is NULL.
  14.  * ''--`` can be used to terminate the scan so that filenames starting
  15.  * with a - can be passed.
  16.  *
  17.  * by Henry Spencer
  18.  * posted to Usenet net.sources list
  19.  * minor changes by D. Spinellis
  20.  */
  21.  
  22. #include <stdio.h>
  23. #include <string.h>
  24.  
  25. char    *optarg;    /* Global argument pointer. */
  26. int    optind = 0;    /* Global argv index. */
  27.  
  28. static char    *scan = NULL;    /* Private scan pointer. */
  29.  
  30.  
  31. int
  32. getopt(argc, argv, optstring)
  33. int argc;
  34. char *argv[];
  35. char *optstring;
  36. {
  37.     register char c;
  38.     register char *place;
  39.  
  40.     optarg = NULL;
  41.  
  42.     if (scan == NULL || *scan == '\0') {
  43.         if (optind == 0)
  44.             optind++;
  45.     
  46.         if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
  47.             return(EOF);
  48.         if (strcmp(argv[optind], "--")==0) {
  49.             optind++;
  50.             return(EOF);
  51.         }
  52.     
  53.         scan = argv[optind]+1;
  54.         optind++;
  55.     }
  56.  
  57.     c = *scan++;
  58.     place = strchr(optstring, c);
  59.  
  60.     if (place == NULL || c == ':') {
  61.         fprintf(stderr, "%s: unknown option -%c\n", argv[0], c);
  62.         return('?');
  63.     }
  64.  
  65.     place++;
  66.     if (*place == ':') {
  67.         if (*scan != '\0') {
  68.             optarg = scan;
  69.             scan = NULL;
  70.         } else if( optind < argc ) {
  71.             optarg = argv[optind];
  72.             optind++;
  73.         }
  74.     }
  75.  
  76.     return(c);
  77. }
  78.