xref: /csrg-svn/lib/libc/stdlib/getopt.c (revision 26524)
121397Smckusick /*
221397Smckusick  * Copyright (c) 1985 Regents of the University of California.
321397Smckusick  * All rights reserved.  The Berkeley software License Agreement
421397Smckusick  * specifies the terms and conditions for redistribution.
521397Smckusick  */
621397Smckusick 
7*26524Sdonn #if defined(LIBC_SCCS) && !defined(lint)
8*26524Sdonn static char sccsid[] = "@(#)getopt.c	4.3 (Berkeley) 03/09/86";
9*26524Sdonn #endif LIBC_SCCS and not lint
1021397Smckusick 
1121397Smckusick #include <stdio.h>
1221397Smckusick 
1321397Smckusick /*
1421397Smckusick  * get option letter from argument vector
1521397Smckusick  */
1625264Smckusick int	opterr = 1,		/* if error message should be printed */
1721397Smckusick 	optind = 1,		/* index into parent argv vector */
1821397Smckusick 	optopt;			/* character checked for validity */
1921397Smckusick char	*optarg;		/* argument associated with option */
2021397Smckusick 
2121397Smckusick #define BADCH	(int)'?'
2221397Smckusick #define EMSG	""
2325264Smckusick #define tell(s)	if (opterr) {fputs(*nargv,stderr);fputs(s,stderr); \
2425264Smckusick 		fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);}
2521397Smckusick 
2621397Smckusick getopt(nargc,nargv,ostr)
2721397Smckusick int	nargc;
2821397Smckusick char	**nargv,
2921397Smckusick 	*ostr;
3021397Smckusick {
3121397Smckusick 	static char	*place = EMSG;	/* option letter processing */
3221397Smckusick 	register char	*oli;		/* option letter list index */
3321397Smckusick 	char	*index();
3421397Smckusick 
3521397Smckusick 	if(!*place) {			/* update scanning pointer */
3621397Smckusick 		if(optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) return(EOF);
3721397Smckusick 		if (*place == '-') {	/* found "--" */
3821397Smckusick 			++optind;
3921397Smckusick 			return(EOF);
4021397Smckusick 		}
4121397Smckusick 	}				/* option letter okay? */
4221397Smckusick 	if ((optopt = (int)*place++) == (int)':' || !(oli = index(ostr,optopt))) {
4321397Smckusick 		if(!*place) ++optind;
4421397Smckusick 		tell(": illegal option -- ");
4521397Smckusick 	}
4621397Smckusick 	if (*++oli != ':') {		/* don't need argument */
4721397Smckusick 		optarg = NULL;
4821397Smckusick 		if (!*place) ++optind;
4921397Smckusick 	}
5021397Smckusick 	else {				/* need an argument */
5121397Smckusick 		if (*place) optarg = place;	/* no white space */
5221397Smckusick 		else if (nargc <= ++optind) {	/* no arg */
5321397Smckusick 			place = EMSG;
5421397Smckusick 			tell(": option requires an argument -- ");
5521397Smckusick 		}
5621397Smckusick 	 	else optarg = nargv[optind];	/* white space */
5721397Smckusick 		place = EMSG;
5821397Smckusick 		++optind;
5921397Smckusick 	}
6021397Smckusick 	return(optopt);			/* dump back option letter */
6121397Smckusick }
62