Berkeley code; correct copyright
[unix-history] / usr / src / lib / libc / stdlib / getopt.c
CommitLineData
a49db6dd
KM
1/*
2 * Copyright (c) 1985 Regents of the University of California.
3 * All rights reserved. The Berkeley software License Agreement
4 * specifies the terms and conditions for redistribution.
5 */
6
2ce81398 7#if defined(LIBC_SCCS) && !defined(lint)
86cd40d8 8static char sccsid[] = "@(#)getopt.c 4.4 (Berkeley) %G%";
2ce81398 9#endif LIBC_SCCS and not lint
a49db6dd
KM
10
11#include <stdio.h>
12
13/*
14 * get option letter from argument vector
15 */
21482c09 16int opterr = 1, /* if error message should be printed */
a49db6dd
KM
17 optind = 1, /* index into parent argv vector */
18 optopt; /* character checked for validity */
19char *optarg; /* argument associated with option */
20
21#define BADCH (int)'?'
22#define EMSG ""
86cd40d8
KB
23#define tell(s) { \
24 if (opterr) { \
25 fputs(*nargv, stderr); \
26 fputs(s, stderr); \
27 fputc(optopt, stderr); \
28 fputc((int)'\n', stderr); \
29 } \
30 return(BADCH); \
31}
a49db6dd 32
86cd40d8
KB
33getopt(nargc, nargv, ostr)
34 int nargc;
35 char **nargv, *ostr;
a49db6dd 36{
86cd40d8
KB
37 static char *place = EMSG; /* option letter processing */
38 register char *oli; /* option letter list index */
a49db6dd
KM
39 char *index();
40
86cd40d8
KB
41 if (!*place) { /* update scanning pointer */
42 if (optind >= nargc || *(place = nargv[optind]) != '-' ||
43 !*++place)
44 return(EOF);
45 if (*place == '-') { /* found "--" */
a49db6dd
KM
46 ++optind;
47 return(EOF);
48 }
86cd40d8
KB
49 } /* option letter okay? */
50 if ((optopt = (int)*place++) == (int)':' ||
51 !(oli = index(ostr, optopt))) {
52 if (!*place)
53 ++optind;
a49db6dd
KM
54 tell(": illegal option -- ");
55 }
86cd40d8 56 if (*++oli != ':') { /* don't need argument */
a49db6dd 57 optarg = NULL;
86cd40d8
KB
58 if (!*place)
59 ++optind;
a49db6dd 60 }
86cd40d8
KB
61 else { /* need an argument */
62 if (*place) /* no white space */
63 optarg = place;
a49db6dd
KM
64 else if (nargc <= ++optind) { /* no arg */
65 place = EMSG;
66 tell(": option requires an argument -- ");
67 }
86cd40d8
KB
68 else /* white space */
69 optarg = nargv[optind];
a49db6dd
KM
70 place = EMSG;
71 ++optind;
72 }
86cd40d8 73 return(optopt); /* dump back option letter */
a49db6dd 74}