1 /* $OpenBSD: getoldopt.c,v 1.9 2009/10/27 23:59:22 deraadt Exp $ */ 2 /* $NetBSD: getoldopt.c,v 1.3 1995/03/21 09:07:28 cgd Exp $ */ 3 4 /*- 5 * Plug-compatible replacement for getopt() for parsing tar-like 6 * arguments. If the first argument begins with "-", it uses getopt; 7 * otherwise, it uses the old rules used by tar, dump, and ps. 8 * 9 * Written 25 August 1985 by John Gilmore (ihnp4!hoptoad!gnu) and placed 10 * in the Public Domain for your edification and enjoyment. 11 */ 12 13 #include <sys/cdefs.h> 14 #include <sys/types.h> 15 #include <sys/stat.h> 16 #include <stdio.h> 17 #include <string.h> 18 #include <unistd.h> 19 20 int getoldopt(int, char **, const char *); 21 22 int 23 getoldopt(int argc, char **argv, const char *optstring) 24 { 25 static char *key; /* Points to next keyletter */ 26 static char use_getopt; /* !=0 if argv[1][0] was '-' */ 27 char c; 28 char *place; 29 30 optarg = NULL; 31 32 if (key == NULL) { /* First time */ 33 if (argc < 2) 34 return (-1); 35 key = argv[1]; 36 if (*key == '-') 37 use_getopt++; 38 else 39 optind = 2; 40 } 41 42 if (use_getopt) 43 return (getopt(argc, argv, optstring)); 44 45 c = *key++; 46 if (c == '\0') { 47 key--; 48 return (-1); 49 } 50 place = strchr(optstring, c); 51 52 if (place == NULL || c == ':') { 53 fprintf(stderr, "%s: unknown option %c\n", argv[0], c); 54 return ('?'); 55 } 56 57 place++; 58 if (*place == ':') { 59 if (optind < argc) { 60 optarg = argv[optind]; 61 optind++; 62 } else { 63 fprintf(stderr, "%s: %c argument missing\n", 64 argv[0], c); 65 return ('?'); 66 } 67 } 68 69 return (c); 70 } 71