file_cmds-202.2.tar.gz
[apple/file_cmds.git] / pax / getoldopt.c
1 /* $OpenBSD: getoldopt.c,v 1.8 2003/07/02 21:19:33 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 Public Domain for your edification and enjoyment.
11 */
12
13 #ifndef lint
14 static const char rcsid[] = "$OpenBSD: getoldopt.c,v 1.8 2003/07/02 21:19:33 deraadt Exp $";
15 #endif /* not lint */
16
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include "pax.h"
23 #include "extern.h"
24
25 int
26 getoldopt(int argc, char **argv, const char *optstring)
27 {
28 static char *key; /* Points to next keyletter */
29 static char use_getopt; /* !=0 if argv[1][0] was '-' */
30 char c;
31 char *place;
32
33 optarg = NULL;
34
35 if (key == NULL) { /* First time */
36 if (argc < 2)
37 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 (getopt(argc, argv, optstring));
47
48 c = *key++;
49 if (c == '\0') {
50 key--;
51 return (-1);
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 }