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