123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
- #include <string.h>
- #include "getopt.h"
- #include <logging/log.h>
- LOG_MODULE_REGISTER(getopt);
- #define BADCH ((int)'?')
- #define BADARG ((int)':')
- #define EMSG ""
- void getopt_init(struct getopt_state *state)
- {
- state->opterr = 1;
- state->optind = 1;
- state->optopt = 0;
- state->optreset = 0;
- state->optarg = NULL;
- state->place = "";
- }
- int
- getopt(state, nargc, nargv, ostr)
- struct getopt_state *state;
- int nargc;
- char *const nargv[];
- const char *ostr;
- {
- char *oli;
- if (state->optreset || *state->place == 0) {
- state->optreset = 0;
- state->place = nargv[state->optind];
- if (state->optind >= nargc || *state->place++ != '-') {
-
- state->place = EMSG;
- return -1;
- }
- state->optopt = *state->place++;
- if (state->optopt == '-' && *state->place == 0) {
-
- ++state->optind;
- state->place = EMSG;
- return -1;
- }
- if (state->optopt == 0) {
-
- state->place = EMSG;
- if (strchr(ostr, '-') == NULL) {
- return -1;
- }
- state->optopt = '-';
- }
- } else {
- state->optopt = *state->place++;
- }
-
- oli = strchr(ostr, state->optopt);
- if (state->optopt == ':' || oli == NULL) {
- if (*state->place == 0) {
- ++state->optind;
- }
- if (state->opterr && *ostr != ':') {
- LOG_ERR("illegal option -- %c", state->optopt);
- }
- return BADCH;
- }
-
- if (oli[1] != ':') {
-
- state->optarg = NULL;
- if (*state->place == 0) {
- ++state->optind;
- }
- } else {
-
- if (*state->place) {
- state->optarg = state->place;
- } else if (nargc > ++state->optind) {
- state->optarg = nargv[state->optind];
- } else {
-
- state->place = EMSG;
- if (*ostr == ':') {
- return BADARG;
- }
- if (state->opterr) {
- LOG_ERR("option requires an argument -- %c",
- state->optopt);
- }
- return BADCH;
- }
- state->place = EMSG;
- ++state->optind;
- }
- return state->optopt;
- }
|