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 #define NULL 0 16 #define EOF (-1) 17 #define ERR(s, c) if(opterr){\ 18 extern int strlen(), write();\ 19 char errbuf[2];\ 20 errbuf[0] = c; errbuf[1] = '\n';\ 21 (void) write(2, argv[0], (unsigned)strlen(argv[0]));\ 22 (void) write(2, s, (unsigned)strlen(s));\ 23 (void) write(2, errbuf, 2);} 24 25 extern int strcmp(); 26 extern char *strchr(); 27 28 int opterr = 1; 29 int optind = 1; 30 int optopt; 31 char *optarg; 32 33 int getopt(int argc, char **argv, char **opts) { 34 static int sp = 1; 35 register int c; 36 register char *cp; 37 38 if(sp == 1) 39 if(optind >= argc || 40 argv[optind][0] != '-' || argv[optind][1] == '\0') 41 return(EOF); 42 else if(strcmp(argv[optind], "--") == NULL) { 43 optind++; 44 return(EOF); 45 } 46 optopt = c = argv[optind][sp]; 47 if(c == ':' || (cp=strchr(opts, c)) == NULL) { 48 ERR(": illegal option -- ", c); 49 if(argv[optind][++sp] == '\0') { 50 optind++; 51 sp = 1; 52 } 53 return('?'); 54 } 55 if(*++cp == ':') { 56 if(argv[optind][sp+1] != '\0') 57 optarg = &argv[optind++][sp+1]; 58 else if(++optind >= argc) { 59 ERR(": option requires an argument -- ", c); 60 sp = 1; 61 return('?'); 62 } else 63 optarg = argv[optind++]; 64 sp = 1; 65 } else { 66 if(argv[optind][++sp] == '\0') { 67 sp = 1; 68 optind++; 69 } 70 optarg = NULL; 71 } 72 return(c); 73 } 74