home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-387-Vol-3of3.iso / d / dshar116.zip / GETOPT.C < prev    next >
C/C++ Source or Header  |  1993-03-08  |  1KB  |  62 lines

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