2 * getopt.c - a simple getopt(3) implementation. See getopt.h for explanation.
4 * Copyright (c) 2007 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2
8 * as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 EXPORT_SYMBOL(optind
);
30 EXPORT_SYMBOL(opterr
);
31 EXPORT_SYMBOL(optopt
);
32 EXPORT_SYMBOL(optarg
);
34 static int optindex
= 1; /* option index in the current argv[] element */
35 static int nonopts
= 0; /* number of nonopts found */
37 void getopt_reset(void)
39 optind
= opterr
= optindex
= 1;
42 EXPORT_SYMBOL(getopt_reset
);
44 int getopt(int argc
, char *argv
[], char *optstring
)
46 char curopt
; /* current option character */
47 char *curoptp
; /* pointer to the current option in optstring */
50 // printf("optindex: %d nonopts: %d optind: %d\n", optindex, nonopts, optind);
52 /* first put nonopts to the end */
53 while (optind
+ nonopts
< argc
&& *argv
[optind
] != '-') {
59 for (i
= optind
; i
+ 1 < argc
; i
++)
60 argv
[i
] = argv
[i
+ 1];
64 if (optind
+ nonopts
>= argc
)
67 /* We have found an option */
68 curopt
= argv
[optind
][optindex
];
71 /* no more options in current argv[] element. Start
72 * over with looking for nonopts
78 /* look up current option in optstring */
79 curoptp
= strchr(optstring
, curopt
);
83 printf("%s: invalid option -- %c\n", argv
[0], curopt
);
89 if (*(curoptp
+ 1) != ':') {
90 /* option with no argument. Just return it */
96 if (*(curoptp
+ 1) && *(curoptp
+ 2) == ':') {
97 /* optional argument */
98 if (argv
[optind
][optindex
+ 1]) {
99 /* optional argument with directly following optarg */
100 optarg
= argv
[optind
] + optindex
+ 1;
105 if (optind
+ nonopts
+ 1 == argc
) {
106 /* We are at the last argv[] element */
111 if (*argv
[optind
+ 1] != '-') {
112 /* optional argument with optarg in next argv[] element
115 optarg
= argv
[optind
];
121 /* no optional argument found */
128 if (argv
[optind
][optindex
+ 1]) {
129 /* required argument with directly following optarg */
130 optarg
= argv
[optind
] + optindex
+ 1;
139 if (optind
+ nonopts
>= argc
|| argv
[optind
][0] == '-') {
141 printf("option requires an argument -- %c\n",
147 optarg
= argv
[optind
];
151 EXPORT_SYMBOL(getopt
);