xref: /csrg-svn/lib/libc/stdlib/getopt.c (revision 32677)
1 /*
2  * Copyright (c) 1987 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of California at Berkeley. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific written prior permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  */
12 
13 #if defined(LIBC_SCCS) && !defined(lint)
14 static char sccsid[] = "@(#)getopt.c	4.5 (Berkeley) 11/24/87";
15 #endif LIBC_SCCS and not lint
16 
17 #include <stdio.h>
18 
19 /*
20  * get option letter from argument vector
21  */
22 int	opterr = 1,		/* if error message should be printed */
23 	optind = 1,		/* index into parent argv vector */
24 	optopt;			/* character checked for validity */
25 char	*optarg;		/* argument associated with option */
26 
27 #define BADCH	(int)'?'
28 #define EMSG	""
29 #define tell(s)	{ \
30 	if (opterr) { \
31 		fputs(*nargv, stderr); \
32 		fputs(s, stderr); \
33 		fputc(optopt, stderr); \
34 		fputc((int)'\n', stderr); \
35 	} \
36 	return(BADCH); \
37 }
38 
39 getopt(nargc, nargv, ostr)
40 	int	nargc;
41 	char	**nargv, *ostr;
42 {
43 	static char	*place = EMSG;		/* option letter processing */
44 	register char	*oli;			/* option letter list index */
45 	char	*index();
46 
47 	if (!*place) {				/* update scanning pointer */
48 		if (optind >= nargc || *(place = nargv[optind]) != '-' ||
49 		    !*++place)
50 			return(EOF);
51 		if (*place == '-') {		/* found "--" */
52 			++optind;
53 			return(EOF);
54 		}
55 	}					/* option letter okay? */
56 	if ((optopt = (int)*place++) == (int)':' ||
57 	    !(oli = index(ostr, optopt))) {
58 		if (!*place)
59 			++optind;
60 		tell(": illegal option -- ");
61 	}
62 	if (*++oli != ':') {			/* don't need argument */
63 		optarg = NULL;
64 		if (!*place)
65 			++optind;
66 	}
67 	else {					/* need an argument */
68 		if (*place)			/* no white space */
69 			optarg = place;
70 		else if (nargc <= ++optind) {	/* no arg */
71 			place = EMSG;
72 			tell(": option requires an argument -- ");
73 		}
74 	 	else				/* white space */
75 			optarg = nargv[optind];
76 		place = EMSG;
77 		++optind;
78 	}
79 	return(optopt);				/* dump back option letter */
80 }
81