home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume18 / smiley / part01 / getopt.c < prev    next >
C/C++ Source or Header  |  1991-04-26  |  2KB  |  62 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(sp == 1)
  27.                 if(optind >= argc ||
  28.                    argv[optind][0] != '-' || argv[optind][1] == '\0')
  29.                         return(-1);
  30.                 else if(strcmp(argv[optind], "--") == 0) {
  31.                         optind++;
  32.                         return(-1);
  33.                 }
  34.         optopt = c = argv[optind][sp];
  35.         if(c == ':' || (cp=strchr(opts, c)) == 0) {
  36.                 ERR(": illegal option -- ", c);
  37.                 if(argv[optind][++sp] == '\0') {
  38.                         optind++;
  39.                         sp = 1;
  40.                 }
  41.                 return('?');
  42.         }
  43.         if(*++cp == ':') {
  44.                 if(argv[optind][sp+1] != '\0')
  45.                         optarg = &argv[optind++][sp+1];
  46.                 else if(++optind >= argc) {
  47.                         ERR(": option requires an argument -- ", c);
  48.                         sp = 1;
  49.                         return('?');
  50.                 } else
  51.                         optarg = argv[optind++];
  52.                 sp = 1;
  53.         } else {
  54.                 if(argv[optind][++sp] == '\0') {
  55.                         sp = 1;
  56.                         optind++;
  57.                 }
  58.                 optarg = 0;
  59.         }
  60.         return(c);
  61. }
  62.