chiark / gitweb /
Merge branch 'master' of git://github.com/stevengj/nlopt
[nlopt.git] / src / util / nlopt-getopt.c
1 #include <stdio.h>
2 #include <string.h>
3 #include "nlopt-getopt.h"
4
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 */
9 char *optarg;                   /* argument associated with option */
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 getopt(int nargc, char *const nargv[], const char *ostr)
20 {
21     static char *place = EMSG;  /* option letter processing */
22     const char *oli;            /* option letter list index */
23     if (optreset || !*place) {  /* update scanning pointer */
24         optreset = 0;
25         if (optind >= nargc || *(place = nargv[optind]) != '-') {
26             place = EMSG;
27             return (-1);
28         }
29         if (place[1] && *++place == '-') {      /* found "--" */
30             ++optind;
31             place = EMSG;
32             return (-1);
33         }
34     }                           /* option letter okay? */
35     if ((optopt = (int) *place++) == (int) ':' || !(oli = strchr(ostr, optopt))) {
36         /* if the user didn't specify '-' as an option, assume it means -1. */
37         if (optopt == (int) '-')
38             return (-1);
39         if (!*place)
40             ++optind;
41         if (opterr && *ostr != ':')
42             (void) printf("illegal option -- %c\n", optopt);
43         return (BADCH);
44     }
45     if (*++oli != ':') {        /* don't need argument */
46         optarg = NULL;
47         if (!*place)
48             ++optind;
49     } else {                    /* need an argument */
50         if (*place)             /* no white space */
51             optarg = place;
52         else if (nargc <= ++optind) {   /* no arg */
53             place = EMSG;
54             if (*ostr == ':')
55                 return (BADARG);
56             if (opterr)
57                 (void) printf("option requires an argument -- %c\n", optopt);
58             return (BADCH);
59         } else                  /* white space */
60             optarg = nargv[optind];
61         place = EMSG;
62         ++optind;
63     }
64     return (optopt);            /* dump back option letter */
65 }