xref: /netbsd-src/bin/pax/getoldopt.c (revision 5e4c038a45edbc7d63b7c2daa76e29f88b64a4e3)
1 /*	$NetBSD: getoldopt.c,v 1.14 2002/01/31 22:43:35 tv 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.14 2002/01/31 22:43:35 tv Exp $");
15 #endif /* not lint */
16 
17 #include <getopt.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <sys/stat.h>
22 #include "pax.h"
23 #include "extern.h"
24 
25 int
26 getoldopt(int argc, char **argv, const char *optstring,
27 	struct option *longopts, int *idx)
28 {
29 	static char	*key;		/* Points to next keyletter */
30 	static char	use_getopt;	/* !=0 if argv[1][0] was '-' */
31 	char		c;
32 	char		*place;
33 
34 	optarg = NULL;
35 
36 	if (key == NULL) {		/* First time */
37 		if (argc < 2) return -1;
38 		key = argv[1];
39 		if (*key == '-')
40 			use_getopt++;
41 		else
42 			optind = 2;
43 	}
44 
45 	if (use_getopt)
46 		return ((longopts != NULL) ?
47 			getopt_long(argc, argv, optstring, longopts, idx) :
48 			getopt(argc, argv, optstring));
49 
50 	c = *key++;
51 	if (c == '\0') {
52 		key--;
53 		return -1;
54 	}
55 	place = strchr(optstring, c);
56 
57 	if (place == NULL || c == ':') {
58 		fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
59 		return('?');
60 	}
61 
62 	place++;
63 	if (*place == ':') {
64 		if (optind < argc) {
65 			optarg = argv[optind];
66 			optind++;
67 		} else {
68 			fprintf(stderr, "%s: %c argument missing\n",
69 				argv[0], c);
70 			return('?');
71 		}
72 	}
73 
74 	return(c);
75 }
76