my previous version was wrong; this one is right
[unix-history] / usr / src / lib / libc / stdlib / getopt.c
CommitLineData
a49db6dd 1/*
cde75055
KB
2 * Copyright (c) 1987 Regents of the University of California.
3 * All rights reserved.
4 *
019bea33 5 * %sccs.include.redist.c%
a49db6dd
KM
6 */
7
2ce81398 8#if defined(LIBC_SCCS) && !defined(lint)
8467f937 9static char sccsid[] = "@(#)getopt.c 4.13 (Berkeley) %G%";
aa5d4ab9 10#endif /* LIBC_SCCS and not lint */
a49db6dd
KM
11
12#include <stdio.h>
8467f937
DS
13#include <stdlib.h>
14#include <string.h>
a49db6dd
KM
15
16/*
17 * get option letter from argument vector
18 */
21482c09 19int opterr = 1, /* if error message should be printed */
a49db6dd
KM
20 optind = 1, /* index into parent argv vector */
21 optopt; /* character checked for validity */
22char *optarg; /* argument associated with option */
23
aa5d4ab9
KB
24#define BADCH (int)'?'
25#define EMSG ""
a49db6dd 26
8467f937 27int
86cd40d8 28getopt(nargc, nargv, ostr)
aa5d4ab9 29 int nargc;
8467f937
DS
30 char * const *nargv;
31 const char *ostr;
a49db6dd 32{
aa5d4ab9
KB
33 static char *place = EMSG; /* option letter processing */
34 register char *oli; /* option letter list index */
8467f937 35 char *p;
a49db6dd 36
86cd40d8 37 if (!*place) { /* update scanning pointer */
eb8159e7
KB
38 if (optind >= nargc || *(place = nargv[optind]) != '-') {
39 place = EMSG;
86cd40d8 40 return(EOF);
eb8159e7 41 }
aa5d4ab9 42 if (place[1] && *++place == '-') { /* found "--" */
a49db6dd 43 ++optind;
eb8159e7 44 place = EMSG;
a49db6dd
KM
45 return(EOF);
46 }
86cd40d8
KB
47 } /* option letter okay? */
48 if ((optopt = (int)*place++) == (int)':' ||
49 !(oli = index(ostr, optopt))) {
dd71e7d8
KB
50 /*
51 * if the user didn't specify '-' as an option,
52 * assume it means EOF.
53 */
54 if (optopt == (int)'-')
55 return(EOF);
86cd40d8
KB
56 if (!*place)
57 ++optind;
c8678857
KB
58 if (opterr) {
59 if (!(p = rindex(*nargv, '/')))
60 p = *nargv;
61 else
62 ++p;
8eb36f35 63 (void)fprintf(stderr, "%s: illegal option -- %c\n",
c8678857
KB
64 p, optopt);
65 }
8eb36f35 66 return(BADCH);
a49db6dd 67 }
86cd40d8 68 if (*++oli != ':') { /* don't need argument */
a49db6dd 69 optarg = NULL;
86cd40d8
KB
70 if (!*place)
71 ++optind;
a49db6dd 72 }
86cd40d8
KB
73 else { /* need an argument */
74 if (*place) /* no white space */
75 optarg = place;
a49db6dd
KM
76 else if (nargc <= ++optind) { /* no arg */
77 place = EMSG;
c8678857
KB
78 if (!(p = rindex(*nargv, '/')))
79 p = *nargv;
80 else
81 ++p;
8eb36f35
KB
82 if (opterr)
83 (void)fprintf(stderr,
84 "%s: option requires an argument -- %c\n",
c8678857 85 p, optopt);
8eb36f35 86 return(BADCH);
a49db6dd 87 }
86cd40d8
KB
88 else /* white space */
89 optarg = nargv[optind];
a49db6dd
KM
90 place = EMSG;
91 ++optind;
92 }
86cd40d8 93 return(optopt); /* dump back option letter */
a49db6dd 94}