Adding upstream version 3.50~pre5.
[syslinux-debian/hramrach.git] / com32 / lib / getopt.c
blob49b007a6464b33d5e7e7be603add30474e1e5389
1 /*
2 * getopt.c
4 * Simple POSIX getopt(), no GNU extensions...
5 */
7 #include <stdint.h>
8 #include <unistd.h>
9 #include <string.h>
11 char *optarg;
12 int optind = 1;
13 int opterr, optopt;
14 static const char *__optptr;
16 int getopt(int argc, char * const *argv, const char *optstring)
18 const char *carg = argv[optind];
19 const char *osptr;
20 int opt;
22 /* We don't actually need argc */
23 (void)argc;
25 /* First, eliminate all non-option cases */
27 if ( !carg || carg[0] != '-' || !carg[1] ) {
28 return -1;
31 if ( carg[1] == '-' && !carg[2] ) {
32 optind++;
33 return -1;
36 if ( (uintptr_t)(__optptr-carg) > (uintptr_t)strlen(carg) )
37 __optptr = carg+1; /* Someone frobbed optind, change to new opt. */
39 opt = *__optptr++;
41 if ( opt != ':' && (osptr = strchr(optstring, opt)) ) {
42 if ( osptr[1] == ':' ) {
43 if ( *__optptr ) {
44 /* Argument-taking option with attached argument */
45 optarg = (char *)__optptr;
46 optind++;
47 } else {
48 /* Argument-taking option with non-attached argument */
49 if ( argv[optind+1] ) {
50 optarg = (char *)argv[optind+1];
51 optind += 2;
52 } else {
53 /* Missing argument */
54 return (optstring[0] == ':') ? ':' : '?';
57 return opt;
58 } else {
59 /* Non-argument-taking option */
60 /* __optptr will remember the exact position to resume at */
61 if ( ! *__optptr )
62 optind++;
63 return opt;
65 } else {
66 /* Unknown option */
67 optopt = opt;
68 if ( ! *__optptr )
69 optind++;
70 return '?';