getoldopt.c revision 1.14.2.2 1 1.14.2.2 jmc /* $NetBSD: getoldopt.c,v 1.14.2.2 2004/06/16 01:27:38 jmc Exp $ */
2 1.3 cgd
3 1.1 jtc /*
4 1.1 jtc * Plug-compatible replacement for getopt() for parsing tar-like
5 1.1 jtc * arguments. If the first argument begins with "-", it uses getopt;
6 1.1 jtc * otherwise, it uses the old rules used by tar, dump, and ps.
7 1.1 jtc *
8 1.1 jtc * Written 25 August 1985 by John Gilmore (ihnp4!hoptoad!gnu) and placed
9 1.4 jtc * in the Public Domain for your edification and enjoyment.
10 1.1 jtc */
11 1.1 jtc
12 1.14.2.2 jmc #if HAVE_CONFIG_H
13 1.14.2.2 jmc #include "config.h"
14 1.14.2.1 jmc #endif
15 1.14.2.1 jmc
16 1.5 christos #include <sys/cdefs.h>
17 1.14.2.1 jmc #if !defined(lint)
18 1.14.2.2 jmc __RCSID("$NetBSD: getoldopt.c,v 1.14.2.2 2004/06/16 01:27:38 jmc Exp $");
19 1.1 jtc #endif /* not lint */
20 1.1 jtc
21 1.14 tv #include <getopt.h>
22 1.1 jtc #include <stdio.h>
23 1.1 jtc #include <string.h>
24 1.14.2.1 jmc #include <stdlib.h>
25 1.2 cgd #include <unistd.h>
26 1.5 christos #include <sys/stat.h>
27 1.5 christos #include "pax.h"
28 1.5 christos #include "extern.h"
29 1.1 jtc
30 1.1 jtc int
31 1.11 lukem getoldopt(int argc, char **argv, const char *optstring,
32 1.12 lukem struct option *longopts, int *idx)
33 1.1 jtc {
34 1.1 jtc static char *key; /* Points to next keyletter */
35 1.1 jtc static char use_getopt; /* !=0 if argv[1][0] was '-' */
36 1.1 jtc char c;
37 1.1 jtc char *place;
38 1.1 jtc
39 1.1 jtc optarg = NULL;
40 1.8 itohy
41 1.1 jtc if (key == NULL) { /* First time */
42 1.6 lukem if (argc < 2) return -1;
43 1.1 jtc key = argv[1];
44 1.1 jtc if (*key == '-')
45 1.1 jtc use_getopt++;
46 1.1 jtc else
47 1.1 jtc optind = 2;
48 1.1 jtc }
49 1.1 jtc
50 1.14.2.1 jmc if (!use_getopt) {
51 1.14.2.1 jmc c = *key++;
52 1.14.2.1 jmc if (c == '\0') {
53 1.14.2.1 jmc key--;
54 1.14.2.1 jmc use_getopt = 1;
55 1.14.2.1 jmc }
56 1.14.2.1 jmc }
57 1.14.2.1 jmc if (use_getopt) {
58 1.14.2.1 jmc if (longopts != NULL) {
59 1.14.2.1 jmc return getopt_long(argc, argv, optstring,
60 1.14.2.1 jmc longopts, idx);
61 1.14.2.1 jmc } else {
62 1.14.2.1 jmc return getopt(argc, argv, optstring);
63 1.14.2.1 jmc }
64 1.1 jtc }
65 1.14.2.1 jmc
66 1.1 jtc place = strchr(optstring, c);
67 1.1 jtc
68 1.1 jtc if (place == NULL || c == ':') {
69 1.1 jtc fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
70 1.1 jtc return('?');
71 1.1 jtc }
72 1.1 jtc
73 1.1 jtc place++;
74 1.1 jtc if (*place == ':') {
75 1.1 jtc if (optind < argc) {
76 1.1 jtc optarg = argv[optind];
77 1.1 jtc optind++;
78 1.1 jtc } else {
79 1.1 jtc fprintf(stderr, "%s: %c argument missing\n",
80 1.1 jtc argv[0], c);
81 1.1 jtc return('?');
82 1.1 jtc }
83 1.1 jtc }
84 1.1 jtc
85 1.1 jtc return(c);
86 1.1 jtc }
87