home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / s / smiley40.zip / GETOPT.C < prev    next >
C/C++ Source or Header  |  1993-01-17  |  2KB  |  68 lines

  1. #define ERR(s, c)       if(opterr){\
  2.         extern int strlen(), write();\
  3.         char errbuf[2];\
  4.         errbuf[0] = c; errbuf[1] = '\n';\
  5.         (void) write(2, argv[0], (unsigned)strlen(argv[0]));\
  6.         (void) write(2, s, (unsigned)strlen(s));\
  7.         (void) write(2, errbuf, 2);}
  8.  
  9. extern int strcmp();
  10. extern char *strchr();
  11.  
  12. int     opterr = 1;
  13. int     optind = 1;
  14. int     optopt;
  15. char    *optarg;
  16.  
  17. int
  18. getopt(argc, argv, opts)
  19. int     argc;
  20. char    **argv, *opts;
  21. {
  22.         static int sp = 1;
  23.         register int c;
  24.         register char *cp;
  25.  
  26.     if(optind == 0)    /* DWS: reset getopt() for reuse */
  27.     {
  28.         optind = 1;
  29.         sp = 1;
  30.     }
  31.  
  32.         if(sp == 1)
  33.                 if(optind >= argc ||
  34.                    argv[optind][0] != '-' || argv[optind][1] == '\0')
  35.                         return(-1);
  36.                 else if(strcmp(argv[optind], "--") == 0) {
  37.                         optind++;
  38.                         return(-1);
  39.                 }
  40.         optopt = c = argv[optind][sp];
  41.         if(c == ':' || (cp=strchr(opts, c)) == 0) {
  42.                 ERR(": illegal option -- ", c);
  43.                 if(argv[optind][++sp] == '\0') {
  44.                         optind++;
  45.                         sp = 1;
  46.                 }
  47.                 return('?');
  48.         }
  49.         if(*++cp == ':') {
  50.                 if(argv[optind][sp+1] != '\0')
  51.                         optarg = &argv[optind++][sp+1];
  52.                 else if(++optind >= argc) {
  53.                         ERR(": option requires an argument -- ", c);
  54.                         sp = 1;
  55.                         return('?');
  56.                 } else
  57.                         optarg = argv[optind++];
  58.                 sp = 1;
  59.         } else {
  60.                 if(argv[optind][++sp] == '\0') {
  61.                         sp = 1;
  62.                         optind++;
  63.                 }
  64.                 optarg = 0;
  65.         }
  66.         return(c);
  67. }
  68.