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