home *** CD-ROM | disk | FTP | other *** search
/ Unix System Administration Handbook 1997 October / usah_oct97.iso / news / cnews.tar / libfake / getopt.c < prev    next >
C/C++ Source or Header  |  1991-03-12  |  1KB  |  63 lines

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