• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 static int opterr = 1;
19 static int optind = 1;
20 static int optopt;
21 static char *optarg;
22 
getopt(int argc,char * argv[],char * opts)23 static int getopt(int argc, char *argv[], char *opts)
24 {
25     static int sp = 1;
26     int c;
27     char *cp;
28 
29     if (sp == 1) {
30         if (optind >= argc ||
31             argv[optind][0] != '-' || argv[optind][1] == '\0')
32             return EOF;
33         else if (!strcmp(argv[optind], "--")) {
34             optind++;
35             return EOF;
36         }
37     }
38     optopt = c = argv[optind][sp];
39     if (c == ':' || !(cp = strchr(opts, c))) {
40         fprintf(stderr, ": illegal option -- %c\n", c);
41         if (argv[optind][++sp] == '\0') {
42             optind++;
43             sp = 1;
44         }
45         return '?';
46     }
47     if (*++cp == ':') {
48         if (argv[optind][sp+1] != '\0')
49             optarg = &argv[optind++][sp+1];
50         else if(++optind >= argc) {
51             fprintf(stderr, ": option requires an argument -- %c\n", c);
52             sp = 1;
53             return '?';
54         } else
55             optarg = argv[optind++];
56         sp = 1;
57     } else {
58         if (argv[optind][++sp] == '\0') {
59             sp = 1;
60             optind++;
61         }
62         optarg = NULL;
63     }
64 
65     return c;
66 }
67