Guido van Rossum | 2508ade | 1994-04-14 14:08:22 +0000 | [diff] [blame] | 1 | /* An implementation of getopt() by Amrit Prem */ |
| 2 | |
| 3 | #include <stdio.h> |
| 4 | #include <string.h> |
| 5 | |
| 6 | #define bool int |
| 7 | #define TRUE 1 |
| 8 | #define FALSE 0 |
| 9 | #define EOS '\0' |
| 10 | |
| 11 | bool opterr = TRUE; /* generate error messages */ |
| 12 | int optind = 1; /* index into argv array */ |
| 13 | char * optarg = NULL; /* optional argument */ |
| 14 | |
| 15 | |
| 16 | int getopt(int argc, char *argv[], const char optstring[]) |
| 17 | { |
| 18 | static char *opt_ptr = ""; |
| 19 | register char *ptr; |
| 20 | int option; |
| 21 | |
| 22 | if (*opt_ptr == EOS) { |
| 23 | |
| 24 | if (optind >= argc || argv[optind][0] != '-') |
| 25 | return -1; |
| 26 | |
| 27 | else if (strcmp(argv[optind], "--") == 0) { |
| 28 | ++optind; |
| 29 | return -1; |
| 30 | } |
| 31 | |
| 32 | opt_ptr = argv[optind++] + 1; |
| 33 | } |
| 34 | |
| 35 | if ((ptr = strchr(optstring, option = *opt_ptr++)) == NULL) { |
| 36 | if (opterr) |
| 37 | fprintf(stderr, "Unknown option: -%c\n", option); |
| 38 | |
| 39 | return '?'; |
| 40 | } |
| 41 | |
| 42 | if (*(ptr + 1) == ':') { |
| 43 | if (optind >= argc) { |
| 44 | if (opterr) |
| 45 | fprintf(stderr, "Argument expected for the -%c option\n", option); |
| 46 | |
| 47 | return '?'; |
| 48 | } |
| 49 | |
| 50 | optarg = argv[optind++]; |
| 51 | } |
| 52 | |
| 53 | return option; |
| 54 | } |