getopt.c revision 225736
1/*
2 * "getopt" routine customized for top.
3 */
4
5/*
6 * Many modern-day Unix implementations already have this function
7 * in libc.  The standard "getopt" is perfectly sufficient for top's
8 * needs.  If such a function exists in libc then you certainly don't
9 * need to compile this one in.  To prevent this function from being
10 * compiled, define "HAVE_GETOPT".  This is usually done in the "CFLAGS"
11 * line of the corresponding machine module.
12 */
13
14/*
15 * This empty declaration exists solely to placate overexhuberant C
16 * compilers that like to warn you about content-free files.
17 */
18static void __empty();
19
20#ifndef HAVE_GETOPT
21
22/*LINTLIBRARY*/
23
24#include "os.h"
25#ifndef NULL
26#define NULL	0
27#endif
28#ifndef EOF
29#define EOF	(-1)
30#endif
31#define ERR(s, c)	if(opterr){\
32	extern int write();\
33	char errbuf[2];\
34	errbuf[0] = c; errbuf[1] = '\n';\
35	(void) write(2, argv[0], strlen(argv[0]));\
36	(void) write(2, s, strlen(s));\
37	(void) write(2, errbuf, 2);}
38
39
40int	opterr = 1;
41int	optind = 1;
42int	optopt;
43char	*optarg;
44
45int
46getopt(argc, argv, opts)
47int	argc;
48char	**argv, *opts;
49{
50	static int sp = 1;
51	register int c;
52	register char *cp;
53
54	if(sp == 1)
55		if(optind >= argc ||
56		   argv[optind][0] != '-' || argv[optind][1] == '\0')
57			return(EOF);
58		else if(strcmp(argv[optind], "--") == 0) {
59			optind++;
60			return(EOF);
61		}
62	optopt = c = argv[optind][sp];
63	if(c == ':' || (cp=strchr(opts, c)) == NULL) {
64		ERR(": unknown option, -", c);
65		if(argv[optind][++sp] == '\0') {
66			optind++;
67			sp = 1;
68		}
69		return('?');
70	}
71	if(*++cp == ':') {
72		if(argv[optind][sp+1] != '\0')
73			optarg = &argv[optind++][sp+1];
74		else if(++optind >= argc) {
75			ERR(": argument missing for -", c);
76			sp = 1;
77			return('?');
78		} else
79			optarg = argv[optind++];
80		sp = 1;
81	} else {
82		if(argv[optind][++sp] == '\0') {
83			sp = 1;
84			optind++;
85		}
86		optarg = NULL;
87	}
88	return(c);
89}
90#endif /* HAVE_GETOPT */
91