xref: /original-bsd/lib/libc/stdlib/getsubopt.c (revision e718337e)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)getsubopt.c	5.1 (Berkeley) 10/30/90";
10 #endif /* not lint */
11 
12 #include <unistd.h>
13 
14 /*
15  * The SVID interface to getsubopt provides no way of figuring out which
16  * part of the suboptions list wasn't matched.  This makes error messages
17  * tricky...  The extern variable suboptarg is a pointer to the token which
18  * didn't match.
19  */
20 char *suboptarg;
21 
22 getsubopt(optionp, tokens, valuep)
23 	register char **optionp, **tokens, **valuep;
24 {
25 	register int cnt;
26 	register char *p;
27 
28 	suboptarg = *valuep = NULL;
29 
30 	if (!optionp || !*optionp)
31 		return(-1);
32 
33 	/* skip leading white-space, commas */
34 	for (p = *optionp; *p && (*p == ',' || *p == ' ' || *p == '\t'); ++p);
35 
36 	if (!*p) {
37 		*optionp = p;
38 		return(-1);
39 	}
40 
41 	/* save the start of the token, and skip the rest of the token. */
42 	for (suboptarg = p;
43 	    *++p && *p != ',' && *p != '=' && *p != ' ' && *p != '\t';);
44 
45 	if (*p) {
46 		/*
47 		 * If there's an equals sign, set the value pointer, and
48 		 * skip over the value part of the token.  Terminate the
49 		 * token.
50 		 */
51 		if (*p == '=') {
52 			*p = '\0';
53 			for (*valuep = ++p;
54 			    *p && *p != ',' && *p != ' ' && *p != '\t'; ++p);
55 			if (*p)
56 				*p++ = '\0';
57 		} else
58 			*p++ = '\0';
59 		/* Skip any whitespace or commas after this token. */
60 		for (; *p && (*p == ',' || *p == ' ' || *p == '\t'); ++p);
61 	}
62 
63 	/* set optionp for next round. */
64 	*optionp = p;
65 
66 	for (cnt = 0; *tokens; ++tokens, ++cnt)
67 		if (!strcmp(suboptarg, *tokens))
68 			return(cnt);
69 	return(-1);
70 }
71