getoldopt.c revision 1.19.2.1
1/*	$NetBSD: getoldopt.c,v 1.19.2.1 2004/06/22 07:25:39 tron 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#if HAVE_NBTOOL_CONFIG_H
13#include "nbtool_config.h"
14#endif
15
16#include <sys/cdefs.h>
17#if !defined(lint)
18__RCSID("$NetBSD: getoldopt.c,v 1.19.2.1 2004/06/22 07:25:39 tron Exp $");
19#endif /* not lint */
20
21#if HAVE_NBTOOL_CONFIG_H
22#include "compat_getopt.h"
23#else
24#include <getopt.h>
25#endif
26#include <stdio.h>
27#include <string.h>
28#include <stdlib.h>
29#include <unistd.h>
30#include <sys/stat.h>
31#include "pax.h"
32#include "extern.h"
33
34int
35getoldopt(int argc, char **argv, const char *optstring,
36	struct option *longopts, int *idx)
37{
38	static char	*key;		/* Points to next keyletter */
39	static char	use_getopt;	/* !=0 if argv[1][0] was '-' */
40	char		c;
41	char		*place;
42
43	optarg = NULL;
44
45	if (key == NULL) {		/* First time */
46		if (argc < 2) return -1;
47		key = argv[1];
48		if (*key == '-')
49			use_getopt++;
50		else
51			optind = 2;
52	}
53
54	if (!use_getopt) {
55		c = *key++;
56		if (c == '\0') {
57			key--;
58			use_getopt = 1;
59		}
60	}
61	if (use_getopt) {
62		if (longopts != NULL) {
63			return getopt_long(argc, argv, optstring,
64			    longopts, idx);
65		} else {
66			return getopt(argc, argv, optstring);
67		}
68	}
69
70	place = strchr(optstring, c);
71
72	if (place == NULL || c == ':') {
73		fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
74		return('?');
75	}
76
77	place++;
78	if (*place == ':') {
79		if (optind < argc) {
80			optarg = argv[optind];
81			optind++;
82		} else {
83			fprintf(stderr, "%s: %c argument missing\n",
84				argv[0], c);
85			return('?');
86		}
87	}
88
89	return(c);
90}
91