home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume16 / pcomm2 / part04 / getopt.c < prev    next >
C/C++ Source or Header  |  1988-09-14  |  1KB  |  56 lines

  1. /*
  2.  * Parse the command line and return option flags and arguments
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. int optind = 1;
  8. char *optarg;
  9.  
  10. int
  11. getopt(argc, argv, opts)
  12. int argc;
  13. char *argv[];
  14. char *opts;
  15. {
  16.     static int sp = 1;
  17.     int c, strcmp();
  18.     char *cp, *strchr();
  19.  
  20.     if (sp == 1) {
  21.         if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
  22.             return(EOF);
  23.         else if (strcmp(argv[optind], "--") == NULL) {
  24.             optind++;
  25.             return(EOF);
  26.         }
  27.     }
  28.     c = argv[optind][sp];
  29.     if (c == ':' || (cp=strchr(opts, c)) == NULL) {
  30.         fprintf(stderr, "%s: illegal option '%c'\n", argv[0], c);
  31.         if (argv[optind][++sp] == '\0') {
  32.             optind++;
  33.             sp = 1;
  34.         }
  35.         return('?');
  36.     }
  37.     if (*++cp == ':') {
  38.         if (argv[optind][sp+1] != '\0')
  39.             optarg = &argv[optind++][sp+1];
  40.         else if (++optind >= argc) {
  41.             fprintf(stderr, "%s: option '%c' requires an argument\n", argv[0], c);
  42.             sp = 1;
  43.             return('?');
  44.         } else
  45.             optarg = argv[optind++];
  46.         sp = 1;
  47.     } else {
  48.         if (argv[optind][++sp] == '\0') {
  49.             sp = 1;
  50.             optind++;
  51.         }
  52.         optarg = NULL;
  53.     }
  54.     return(c);
  55. }
  56.