blob: 81af41059babae1661677eed7242d37affbd80f8 [file] [log] [blame]
Sergi Àlvarez i Capillacff66502017-07-04 09:55:46 +02001#include <string.h>
2#include <stdio.h>
3
4// global
5int opterr = 1, /* if error message should be printed */
6optind = 1, /* index into parent argv vector */
7optopt, /* character checked for validity */
8optreset; /* reset getopt */
Nguyen Anh Quynh2fc852d2018-07-24 01:41:59 +08009const char *optarg; /* argument associated with option */
Sergi Àlvarez i Capillacff66502017-07-04 09:55:46 +020010
11#define BADCH (int)'?'
12#define BADARG (int)':'
13#define EMSG ""
14
15/*
16 * getopt --
17 * Parse argc/argv argument vector.
18 */
19int
20getopt (int nargc, char * const nargv[], const char *ostr)
21{
Nguyen Anh Quynh2fc852d2018-07-24 01:41:59 +080022 static const char *place = EMSG; /* option letter processing */
Sergi Àlvarez i Capillacff66502017-07-04 09:55:46 +020023 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}