Home | History | Annotate | Line # | Download | only in compat
      1 #include <stdio.h>
      2 #include <string.h>
      3 #include "getopt.h"
      4 
      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  * There is no manual page.  That is because the one they gave out at
     13  * UNIFORUM was slightly different from the current System V Release 2
     14  * manual page.  The difference apparently involved a note about the
     15  * famous rules 5 and 6, recommending using white space between an option
     16  * and its first argument, and not grouping options that have arguments.
     17  * Getopt itself is currently lenient about both of these things White
     18  * space is allowed, but not mandatory, and the last option in a group can
     19  * have an argument.  That particular version of the man page evidently
     20  * has no official existence, and my source at AT&T did not send a copy.
     21  * The current SVR2 man page reflects the actual behavior of this getopt.
     22  * However, I am not about to post a copy of anything licensed by AT&T.
     23  */
     24 
     25 #define ERR(szz,czz) if(opterr){fprintf(stderr,"%s%s%c\n",argv[0],szz,czz);}
     26 
     27 int opterr = 1;
     28 int optind = 1;
     29 int optopt;
     30 char *optarg;
     31 
     32 int
     33 getopt(
     34     int argc,
     35     char **argv,
     36     const char *opts)
     37 {
     38     static int sp = 1;
     39     register int c;
     40     register char *cp;
     41 
     42     if (sp == 1) {
     43 	if (optind >= argc ||
     44 	    argv[optind][0] != '-' || argv[optind][1] == '\0')
     45 	    return (EOF);
     46 	else if (strcmp(argv[optind], "--") == 0) {
     47 	    optind++;
     48 	    return (EOF);
     49 	}
     50     }
     51     optopt = c = argv[optind][sp];
     52     if (c == ':' || (cp = strchr(opts, c)) == NULL) {
     53 	ERR(": illegal option -- ", c);
     54 	if (argv[optind][++sp] == '\0') {
     55 	    optind++;
     56 	    sp = 1;
     57 	}
     58 	return ('?');
     59     }
     60     if (*++cp == ':') {
     61 	if (argv[optind][sp + 1] != '\0')
     62 	    optarg = &argv[optind++][sp + 1];
     63 	else if (++optind >= argc) {
     64 	    ERR(": option requires an argument -- ", c);
     65 	    sp = 1;
     66 	    return ('?');
     67 	} else
     68 	    optarg = argv[optind++];
     69 	sp = 1;
     70     } else {
     71 	if (argv[optind][++sp] == '\0') {
     72 	    sp = 1;
     73 	    optind++;
     74 	}
     75 	optarg = NULL;
     76     }
     77     return (c);
     78 }
     79