xref: /original-bsd/lib/libc/stdlib/getopt.c (revision 69c8e3e7)
1 /*
2  * Copyright (c) 1987, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)getopt.c	8.1 (Berkeley) 06/04/93";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 
16 /*
17  * get option letter from argument vector
18  */
19 int	opterr = 1,		/* if error message should be printed */
20 	optind = 1,		/* index into parent argv vector */
21 	optopt,			/* character checked for validity */
22 	optreset;		/* reset getopt */
23 char	*optarg;		/* argument associated with option */
24 
25 #define	BADCH	(int)'?'
26 #define	BADARG	(int)':'
27 #define	EMSG	""
28 
29 int
30 getopt(nargc, nargv, ostr)
31 	int nargc;
32 	char * const *nargv;
33 	const char *ostr;
34 {
35 	static char *place = EMSG;		/* option letter processing */
36 	register char *oli;			/* option letter list index */
37 	char *p;
38 
39 	if (optreset || !*place) {		/* update scanning pointer */
40 		optreset = 0;
41 		if (optind >= nargc || *(place = nargv[optind]) != '-') {
42 			place = EMSG;
43 			return(EOF);
44 		}
45 		if (place[1] && *++place == '-') {	/* found "--" */
46 			++optind;
47 			place = EMSG;
48 			return(EOF);
49 		}
50 	}					/* option letter okay? */
51 	if ((optopt = (int)*place++) == (int)':' ||
52 	    !(oli = index(ostr, optopt))) {
53 		/*
54 		 * if the user didn't specify '-' as an option,
55 		 * assume it means EOF.
56 		 */
57 		if (optopt == (int)'-')
58 			return(EOF);
59 		if (!*place)
60 			++optind;
61 		if (opterr && *ostr != ':') {
62 			if (!(p = rindex(*nargv, '/')))
63 				p = *nargv;
64 			else
65 				++p;
66 			(void)fprintf(stderr, "%s: illegal option -- %c\n",
67 			    p, optopt);
68 		}
69 		return(BADCH);
70 	}
71 	if (*++oli != ':') {			/* don't need argument */
72 		optarg = NULL;
73 		if (!*place)
74 			++optind;
75 	}
76 	else {					/* need an argument */
77 		if (*place)			/* no white space */
78 			optarg = place;
79 		else if (nargc <= ++optind) {	/* no arg */
80 			place = EMSG;
81 			if (!(p = rindex(*nargv, '/')))
82 				p = *nargv;
83 			else
84 				++p;
85 			if (*ostr == ':')
86 				return(BADARG);
87 			if (opterr)
88 				(void)fprintf(stderr,
89 				    "%s: option requires an argument -- %c\n",
90 				    p, optopt);
91 			return(BADCH);
92 		}
93 	 	else				/* white space */
94 			optarg = nargv[optind];
95 		place = EMSG;
96 		++optind;
97 	}
98 	return(optopt);				/* dump back option letter */
99 }
100