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