1 /* $OpenBSD: getopt.c,v 1.1 1999/10/01 01:08:29 angelos Exp $ */
2
3 #include "config.h"
4
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8
9 /*** getopt
10 *
11 * This function is the public domain version of getopt, the command
12 * line argument processor, and hence is NOT copyrighted by Microsoft,
13 * IBM, or AT&T.
14 */
15
16 #define ERR(s, c) if(opterr){\
17 (void) fputs(argv[0], stderr);\
18 (void) fputs(s, stderr);\
19 (void) fputc(c, stderr);\
20 (void) fputc('\n', stderr);}
21
22 int opterr = 1; /* flag:error message on unrecognzed options */
23 int optind = 1; /* last touched cmdline argument */
24 int optopt; /* last returned option */
25 char *optarg; /* argument to optopt */
26
27 /* int argc is the number of arguments on cmdline */
28 /* char **argv is the pointer to array of cmdline arguments */
29 /* char *opts is the string of all valid options */
30 /* each char case must be given; options taking an arg are followed by =
31 ':' */
getopt(int argc,char * const * argv,const char * opts)32 int getopt(int argc, char * const *argv, const char *opts)
33 {
34 static int sp = 1;
35 register int c;
36 register char *cp;
37 if(sp == 1) {
38 /* check for end of options */
39 if(optind >= argc ||
40 (argv[optind][0] != '/' &&
41 argv[optind][0] != '-') ||
42 argv[optind][1] == '\0')
43 return(EOF);
44 else if(!strcmp(argv[optind], "--")) {
45 optind++;
46 return(EOF);
47 }
48 }
49 optopt = c = argv[optind][sp];
50 if(c == ':' || (cp=strchr(opts, c)) == NULL) {
51 /* if arg sentinel as option or other invalid option,
52 handle the error and return '?' */
53 ERR(": illegal option -- ", (char)c);
54 if(argv[optind][++sp] == '\0') {
55 optind++;
56 sp = 1;
57 }
58 return('?');
59 }
60 if(*++cp == ':') {
61 /* if option is given an argument... */
62 if(argv[optind][sp+1] != '\0')
63 /* and the OptArg is in that CmdLineArg, return it... */
64 optarg = &argv[optind++][sp+1];
65 else if(++optind >= argc) {
66 /* but if the OptArg isn't there and the next CmdLineArg
67 isn't either, handle the error... */
68 ERR(": option requires an argument -- ", (char)c);
69 sp = 1;
70 return('?');
71 } else
72 /* but if there is another CmdLineArg there, return that */
73 optarg = argv[optind++];
74 /* and set up for the next CmdLineArg */
75 sp = 1;
76 } else {
77 /* no arg for this opt, so null arg and set up for next option */
78 if(argv[optind][++sp] == '\0') {
79 sp = 1;
80 optind++;
81 }
82 optarg = NULL;
83 }
84 return(c);
85 }
86