home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / cawf407.zip / src / getopt.c < prev    next >
C/C++ Source or Header  |  1993-12-28  |  2KB  |  88 lines

  1. /*
  2. Newsgroups: mod.std.unix
  3. Subject: public domain AT&T getopt source
  4. Date: 3 Nov 85 19:34:15 GMT
  5.  
  6. Here's something you've all been waiting for:  the AT&T public domain
  7. source for getopt(3).  It is the code which was given out at the 1985
  8. UNIFORUM conference in Dallas.  I obtained it by electronic mail
  9. directly from AT&T.  The people there assure me that it is indeed
  10. in the public domain.
  11. */
  12.  
  13.  
  14. /*LINTLIBRARY*/
  15.  
  16. #ifdef    UNIX
  17. # if    !defined(_NEXT_SOURCE)
  18. extern int strlen();
  19. # endif
  20. extern int strcmp();
  21. extern char *strchr();
  22. extern int write();
  23. #else
  24. #include <io.h>
  25. #include <string.h>
  26. #endif
  27.  
  28. #define NULL    0
  29. #define EOF    (-1)
  30. #define ERR(s, c)    if(opterr){\
  31.     char errbuf[2];\
  32.     errbuf[0] = c; errbuf[1] = '\n';\
  33.     (void) write(2, argv[0], (unsigned)strlen(argv[0]));\
  34.     (void) write(2, s, (unsigned)strlen(s));\
  35.     (void) write(2, errbuf, 2);}
  36.  
  37.  
  38. int    opterr = 1;
  39. int    optind = 1;
  40. int    optopt;
  41. char    *optarg;
  42.  
  43. int
  44. getopt(argc, argv, opts)
  45. int    argc;
  46. char    **argv, *opts;
  47. {
  48.     static int sp = 1;
  49.     register int c;
  50.     register char *cp;
  51.  
  52.     if(sp == 1)
  53.         if(optind >= argc ||
  54.            argv[optind][0] != '-' || argv[optind][1] == '\0')
  55.             return(EOF);
  56.         else if(strcmp(argv[optind], "--") == NULL) {
  57.             optind++;
  58.             return(EOF);
  59.         }
  60.     optopt = c = argv[optind][sp];
  61.     if(c == ':' || (cp=strchr(opts, c)) == NULL) {
  62.         ERR(": illegal option -- ", c);
  63.         if(argv[optind][++sp] == '\0') {
  64.             optind++;
  65.             sp = 1;
  66.         }
  67.         return('?');
  68.     }
  69.     if(*++cp == ':') {
  70.         if(argv[optind][sp+1] != '\0')
  71.             optarg = &argv[optind++][sp+1];
  72.         else if(++optind >= argc) {
  73.             ERR(": option requires an argument -- ", c);
  74.             sp = 1;
  75.             return('?');
  76.         } else
  77.             optarg = argv[optind++];
  78.         sp = 1;
  79.     } else {
  80.         if(argv[optind][++sp] == '\0') {
  81.             sp = 1;
  82.             optind++;
  83.         }
  84.         optarg = NULL;
  85.     }
  86.     return(c);
  87. }
  88.