getoldopt.c revision 1.23
1/* $NetBSD: getoldopt.c,v 1.23 2012/08/09 11:05:59 christos 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.23 2012/08/09 11:05:59 christos 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 <stdint.h> 31#include <sys/stat.h> 32#include "pax.h" 33#include "extern.h" 34 35int 36getoldopt(int argc, char **argv, const char *optstring, 37 struct option *longopts, int *idx) 38{ 39 static char *key; /* Points to next keyletter */ 40 static char use_getopt; /* !=0 if argv[1][0] was '-' */ 41 char c; 42 char *place; 43 44 optarg = NULL; 45 46 if (key == NULL) { /* First time */ 47 if (argc < 2) return -1; 48 key = argv[1]; 49 if (*key == '-') 50 use_getopt++; 51 else 52 optind = 2; 53 } 54 55 c = '\0'; 56 if (!use_getopt) { 57 c = *key++; 58 if (c == '\0') { 59 key--; 60 use_getopt = 1; 61 } 62 } 63 if (use_getopt) { 64 if (longopts != NULL) { 65 return getopt_long(argc, argv, optstring, 66 longopts, idx); 67 } else { 68 return getopt(argc, argv, optstring); 69 } 70 } 71 72 place = strchr(optstring, c); 73 74 if (place == NULL || c == ':') { 75 fprintf(stderr, "%s: unknown option %c\n", argv[0], c); 76 return '?'; 77 } 78 79 place++; 80 if (*place == ':') { 81 if (optind < argc) { 82 optarg = argv[optind]; 83 optind++; 84 } else { 85 fprintf(stderr, "%s: %c argument missing\n", 86 argv[0], c); 87 return '?'; 88 } 89 } 90 91 return c; 92} 93