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