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