getoldopt.c revision 1.2
1/*
2 * Plug-compatible replacement for getopt() for parsing tar-like
3 * arguments.  If the first argument begins with "-", it uses getopt;
4 * otherwise, it uses the old rules used by tar, dump, and ps.
5 *
6 * Written 25 August 1985 by John Gilmore (ihnp4!hoptoad!gnu) and placed
7 * in the Pubic Domain for your edification and enjoyment.
8 */
9
10#ifndef lint
11static char *rcsid = "$Id: getoldopt.c,v 1.2 1994/12/04 07:11:53 cgd Exp $";
12#endif /* not lint */
13
14#include <stdio.h>
15#include <string.h>
16#include <unistd.h>
17
18int
19getoldopt(argc, argv, optstring)
20	int	argc;
21	char	**argv;
22	char	*optstring;
23{
24	extern char	*optarg;	/* Points to next arg */
25	extern int	optind;		/* Global argv index */
26	static char	*key;		/* Points to next keyletter */
27	static char	use_getopt;	/* !=0 if argv[1][0] was '-' */
28	char		c;
29	char		*place;
30
31	optarg = NULL;
32
33	if (key == NULL) {		/* First time */
34		if (argc < 2) return EOF;
35		key = argv[1];
36		if (*key == '-')
37			use_getopt++;
38		else
39			optind = 2;
40	}
41
42	if (use_getopt)
43		return getopt(argc, argv, optstring);
44
45	c = *key++;
46	if (c == '\0') {
47		key--;
48		return EOF;
49	}
50	place = strchr(optstring, c);
51
52	if (place == NULL || c == ':') {
53		fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
54		return('?');
55	}
56
57	place++;
58	if (*place == ':') {
59		if (optind < argc) {
60			optarg = argv[optind];
61			optind++;
62		} else {
63			fprintf(stderr, "%s: %c argument missing\n",
64				argv[0], c);
65			return('?');
66		}
67	}
68
69	return(c);
70}
71