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