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