1 /* $NetBSD: getopt.c,v 1.1.1.1 2009/12/13 16:55:02 kardel Exp $ */ 2 3 /* 4 * getopt - get option letter from argv 5 * 6 * This is a version of the public domain getopt() implementation by 7 * Henry Spencer, changed for 4.3BSD compatibility (in addition to System V). 8 * It allows rescanning of an option list by setting optind to 0 before 9 * calling, which is why we use it even if the system has its own (in fact, 10 * this one has a unique name so as not to conflict with the system's). 11 * Thanks to Dennis Ferguson for the appropriate modifications. 12 * 13 * This file is in the Public Domain. 14 */ 15 16 /*LINTLIBRARY*/ 17 18 #include <stdio.h> 19 20 #include "ntp_stdlib.h" 21 22 #ifdef lint 23 #undef putc 24 #define putc fputc 25 #endif /* lint */ 26 27 char *ntp_optarg; /* Global argument pointer. */ 28 int ntp_optind = 0; /* Global argv index. */ 29 int ntp_opterr = 1; /* for compatibility, should error be printed? */ 30 int ntp_optopt; /* for compatibility, option character checked */ 31 32 static char *scan = NULL; /* Private scan pointer. */ 33 static const char *prog = "amnesia"; 34 35 /* 36 * Print message about a bad option. 37 */ 38 static int 39 badopt( 40 const char *mess, 41 int ch 42 ) 43 { 44 if (ntp_opterr) { 45 fputs(prog, stderr); 46 fputs(mess, stderr); 47 (void) putc(ch, stderr); 48 (void) putc('\n', stderr); 49 } 50 return ('?'); 51 } 52 53 int 54 ntp_getopt( 55 int argc, 56 char *argv[], 57 const char *optstring 58 ) 59 { 60 register char c; 61 register const char *place; 62 63 prog = argv[0]; 64 ntp_optarg = NULL; 65 66 if (ntp_optind == 0) { 67 scan = NULL; 68 ntp_optind++; 69 } 70 71 if (scan == NULL || *scan == '\0') { 72 if (ntp_optind >= argc 73 || argv[ntp_optind][0] != '-' 74 || argv[ntp_optind][1] == '\0') { 75 return (EOF); 76 } 77 if (argv[ntp_optind][1] == '-' 78 && argv[ntp_optind][2] == '\0') { 79 ntp_optind++; 80 return (EOF); 81 } 82 83 scan = argv[ntp_optind++]+1; 84 } 85 86 c = *scan++; 87 ntp_optopt = c & 0377; 88 for (place = optstring; place != NULL && *place != '\0'; ++place) 89 if (*place == c) 90 break; 91 92 if (place == NULL || *place == '\0' || c == ':' || c == '?') { 93 return (badopt(": unknown option -", c)); 94 } 95 96 place++; 97 if (*place == ':') { 98 if (*scan != '\0') { 99 ntp_optarg = scan; 100 scan = NULL; 101 } else if (ntp_optind >= argc) { 102 return (badopt(": option requires argument -", c)); 103 } else { 104 ntp_optarg = argv[ntp_optind++]; 105 } 106 } 107 108 return (c & 0377); 109 } 110