xref: /csrg-svn/lib/libc/stdlib/getopt.c (revision 21397)
1*21397Smckusick /*
2*21397Smckusick  * Copyright (c) 1985 Regents of the University of California.
3*21397Smckusick  * All rights reserved.  The Berkeley software License Agreement
4*21397Smckusick  * specifies the terms and conditions for redistribution.
5*21397Smckusick  */
6*21397Smckusick 
7*21397Smckusick #ifndef lint
8*21397Smckusick static char sccsid[] = "@(#)getopt.c	4.1 (Berkeley) 05/30/85";
9*21397Smckusick #endif not lint
10*21397Smckusick 
11*21397Smckusick #include <stdio.h>
12*21397Smckusick 
13*21397Smckusick /*
14*21397Smckusick  * get option letter from argument vector
15*21397Smckusick  */
16*21397Smckusick int	opterr = 1,		/* useless, never set or used */
17*21397Smckusick 	optind = 1,		/* index into parent argv vector */
18*21397Smckusick 	optopt;			/* character checked for validity */
19*21397Smckusick char	*optarg;		/* argument associated with option */
20*21397Smckusick 
21*21397Smckusick #define BADCH	(int)'?'
22*21397Smckusick #define EMSG	""
23*21397Smckusick #define tell(s)	fputs(*nargv,stderr);fputs(s,stderr); \
24*21397Smckusick 		fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);
25*21397Smckusick 
26*21397Smckusick getopt(nargc,nargv,ostr)
27*21397Smckusick int	nargc;
28*21397Smckusick char	**nargv,
29*21397Smckusick 	*ostr;
30*21397Smckusick {
31*21397Smckusick 	static char	*place = EMSG;	/* option letter processing */
32*21397Smckusick 	register char	*oli;		/* option letter list index */
33*21397Smckusick 	char	*index();
34*21397Smckusick 
35*21397Smckusick 	if(!*place) {			/* update scanning pointer */
36*21397Smckusick 		if(optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) return(EOF);
37*21397Smckusick 		if (*place == '-') {	/* found "--" */
38*21397Smckusick 			++optind;
39*21397Smckusick 			return(EOF);
40*21397Smckusick 		}
41*21397Smckusick 	}				/* option letter okay? */
42*21397Smckusick 	if ((optopt = (int)*place++) == (int)':' || !(oli = index(ostr,optopt))) {
43*21397Smckusick 		if(!*place) ++optind;
44*21397Smckusick 		tell(": illegal option -- ");
45*21397Smckusick 	}
46*21397Smckusick 	if (*++oli != ':') {		/* don't need argument */
47*21397Smckusick 		optarg = NULL;
48*21397Smckusick 		if (!*place) ++optind;
49*21397Smckusick 	}
50*21397Smckusick 	else {				/* need an argument */
51*21397Smckusick 		if (*place) optarg = place;	/* no white space */
52*21397Smckusick 		else if (nargc <= ++optind) {	/* no arg */
53*21397Smckusick 			place = EMSG;
54*21397Smckusick 			tell(": option requires an argument -- ");
55*21397Smckusick 		}
56*21397Smckusick 	 	else optarg = nargv[optind];	/* white space */
57*21397Smckusick 		place = EMSG;
58*21397Smckusick 		++optind;
59*21397Smckusick 	}
60*21397Smckusick 	return(optopt);			/* dump back option letter */
61*21397Smckusick }
62