xref: /openbsd/bin/pax/getoldopt.c (revision 09e94acb)
1 /*	$OpenBSD: getoldopt.c,v 1.2 1996/06/23 14:20:36 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.2 1996/06/23 14:20:36 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 	extern char	*optarg;	/* Points to next arg */
28 	extern int	optind;		/* Global argv index */
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 EOF;
38 		key = argv[1];
39 		if (*key == '-')
40 			use_getopt++;
41 		else
42 			optind = 2;
43 	}
44 
45 	if (use_getopt)
46 		return getopt(argc, argv, optstring);
47 
48 	c = *key++;
49 	if (c == '\0') {
50 		key--;
51 		return EOF;
52 	}
53 	place = strchr(optstring, c);
54 
55 	if (place == NULL || c == ':') {
56 		fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
57 		return('?');
58 	}
59 
60 	place++;
61 	if (*place == ':') {
62 		if (optind < argc) {
63 			optarg = argv[optind];
64 			optind++;
65 		} else {
66 			fprintf(stderr, "%s: %c argument missing\n",
67 				argv[0], c);
68 			return('?');
69 		}
70 	}
71 
72 	return(c);
73 }
74