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