getoldopt.c revision 1.4 1 1.4 jtc /* $NetBSD: getoldopt.c,v 1.4 1996/05/17 01:07:47 jtc 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.1 jtc #ifndef lint
13 1.4 jtc static char rcsid[] = "$NetBSD: getoldopt.c,v 1.4 1996/05/17 01:07:47 jtc Exp $";
14 1.1 jtc #endif /* not lint */
15 1.1 jtc
16 1.1 jtc #include <stdio.h>
17 1.1 jtc #include <string.h>
18 1.2 cgd #include <unistd.h>
19 1.1 jtc
20 1.1 jtc int
21 1.1 jtc getoldopt(argc, argv, optstring)
22 1.1 jtc int argc;
23 1.1 jtc char **argv;
24 1.1 jtc char *optstring;
25 1.1 jtc {
26 1.1 jtc extern char *optarg; /* Points to next arg */
27 1.1 jtc extern int optind; /* Global argv index */
28 1.1 jtc static char *key; /* Points to next keyletter */
29 1.1 jtc static char use_getopt; /* !=0 if argv[1][0] was '-' */
30 1.1 jtc char c;
31 1.1 jtc char *place;
32 1.1 jtc
33 1.1 jtc optarg = NULL;
34 1.1 jtc
35 1.1 jtc if (key == NULL) { /* First time */
36 1.1 jtc if (argc < 2) return EOF;
37 1.1 jtc key = argv[1];
38 1.1 jtc if (*key == '-')
39 1.1 jtc use_getopt++;
40 1.1 jtc else
41 1.1 jtc optind = 2;
42 1.1 jtc }
43 1.1 jtc
44 1.1 jtc if (use_getopt)
45 1.1 jtc return getopt(argc, argv, optstring);
46 1.1 jtc
47 1.1 jtc c = *key++;
48 1.1 jtc if (c == '\0') {
49 1.1 jtc key--;
50 1.1 jtc return EOF;
51 1.1 jtc }
52 1.1 jtc place = strchr(optstring, c);
53 1.1 jtc
54 1.1 jtc if (place == NULL || c == ':') {
55 1.1 jtc fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
56 1.1 jtc return('?');
57 1.1 jtc }
58 1.1 jtc
59 1.1 jtc place++;
60 1.1 jtc if (*place == ':') {
61 1.1 jtc if (optind < argc) {
62 1.1 jtc optarg = argv[optind];
63 1.1 jtc optind++;
64 1.1 jtc } else {
65 1.1 jtc fprintf(stderr, "%s: %c argument missing\n",
66 1.1 jtc argv[0], c);
67 1.1 jtc return('?');
68 1.1 jtc }
69 1.1 jtc }
70 1.1 jtc
71 1.1 jtc return(c);
72 1.1 jtc }
73