xref: /csrg-svn/lib/libc/stdlib/getopt.c (revision 34017)
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.6 (Berkeley) 04/19/88";
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 			return(EOF);
50 		if (place[1] && *++place == '-') {	/* found "--" */
51 			++optind;
52 			return(EOF);
53 		}
54 	}					/* option letter okay? */
55 	if ((optopt = (int)*place++) == (int)':' ||
56 	    !(oli = index(ostr, optopt))) {
57 		if (!*place)
58 			++optind;
59 		tell(": illegal option -- ");
60 	}
61 	if (*++oli != ':') {			/* don't need argument */
62 		optarg = NULL;
63 		if (!*place)
64 			++optind;
65 	}
66 	else {					/* need an argument */
67 		if (*place)			/* no white space */
68 			optarg = place;
69 		else if (nargc <= ++optind) {	/* no arg */
70 			place = EMSG;
71 			tell(": option requires an argument -- ");
72 		}
73 	 	else				/* white space */
74 			optarg = nargv[optind];
75 		place = EMSG;
76 		++optind;
77 	}
78 	return(optopt);				/* dump back option letter */
79 }
80