Sergi Àlvarez i Capilla | cff6650 | 2017-07-04 09:55:46 +0200 | [diff] [blame] | 1 | #include <string.h> |
| 2 | #include <stdio.h> |
| 3 | |
| 4 | // global |
| 5 | int opterr = 1, /* if error message should be printed */ |
| 6 | optind = 1, /* index into parent argv vector */ |
| 7 | optopt, /* character checked for validity */ |
| 8 | optreset; /* reset getopt */ |
Nguyen Anh Quynh | 2fc852d | 2018-07-24 01:41:59 +0800 | [diff] [blame] | 9 | const char *optarg; /* argument associated with option */ |
Sergi Àlvarez i Capilla | cff6650 | 2017-07-04 09:55:46 +0200 | [diff] [blame] | 10 | |
| 11 | #define BADCH (int)'?' |
| 12 | #define BADARG (int)':' |
| 13 | #define EMSG "" |
| 14 | |
| 15 | /* |
| 16 | * getopt -- |
| 17 | * Parse argc/argv argument vector. |
| 18 | */ |
| 19 | int |
| 20 | getopt (int nargc, char * const nargv[], const char *ostr) |
| 21 | { |
Nguyen Anh Quynh | 2fc852d | 2018-07-24 01:41:59 +0800 | [diff] [blame] | 22 | static const char *place = EMSG; /* option letter processing */ |
Sergi Àlvarez i Capilla | cff6650 | 2017-07-04 09:55:46 +0200 | [diff] [blame] | 23 | const char *oli; /* option letter list index */ |
| 24 | |
| 25 | if (optreset || !*place) { /* update scanning pointer */ |
| 26 | optreset = 0; |
| 27 | if (optind >= nargc || *(place = nargv[optind]) != '-') { |
| 28 | place = EMSG; |
| 29 | return (-1); |
| 30 | } |
| 31 | if (place[1] && *++place == '-') { /* found "--" */ |
| 32 | ++optind; |
| 33 | place = EMSG; |
| 34 | return (-1); |
| 35 | } |
| 36 | } /* option letter okay? */ |
| 37 | if ((optopt = (int)*place++) == (int)':' || |
| 38 | !(oli = strchr (ostr, optopt))) { |
| 39 | /* |
| 40 | * if the user didn't specify '-' as an option, |
| 41 | * assume it means -1. |
| 42 | */ |
| 43 | if (optopt == (int)'-') |
| 44 | return (-1); |
| 45 | if (!*place) |
| 46 | ++optind; |
| 47 | if (opterr && *ostr != ':') |
| 48 | (void)printf ("illegal option -- %c\n", optopt); |
| 49 | return (BADCH); |
| 50 | } |
| 51 | if (*++oli != ':') { /* don't need argument */ |
| 52 | optarg = NULL; |
| 53 | if (!*place) |
| 54 | ++optind; |
| 55 | } |
| 56 | else { /* need an argument */ |
| 57 | if (*place) /* no white space */ |
| 58 | optarg = place; |
| 59 | else if (nargc <= ++optind) { /* no arg */ |
| 60 | place = EMSG; |
| 61 | if (*ostr == ':') |
| 62 | return (BADARG); |
| 63 | if (opterr) |
| 64 | (void)printf ("option requires an argument -- %c\n", optopt); |
| 65 | return (BADCH); |
| 66 | } |
| 67 | else /* white space */ |
| 68 | optarg = nargv[optind]; |
| 69 | place = EMSG; |
| 70 | ++optind; |
| 71 | } |
| 72 | return optopt; /* dump back option letter */ |
| 73 | } |