chiark / gitweb /
put source code into src subdirectory
[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     }
50     else {                                  /* need an argument */
51         if (*place)                         /* no white space */
52             optarg = place;
53         else if (nargc <= ++optind) {       /* no arg */
54             place = EMSG;
55             if (*ostr == ':')
56                 return (BADARG);
57             if (opterr)
58                 (void) printf("option requires an argument -- %c\n", optopt);
59             return (BADCH);
60         }
61         else                                /* white space */
62             optarg = nargv[optind];
63         place = EMSG;
64         ++optind;
65     }
66     return (optopt);                        /* dump back option letter */
67 }