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