File: fetchopt.cc

package info (click to toggle)
simutrans 111.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 13,504 kB
  • ctags: 12,645
  • sloc: cpp: 101,849; ansic: 3,466; makefile: 694; sh: 44
file content (67 lines) | stat: -rw-r--r-- 1,209 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* fetchopt.cc
 *
 * Options parsing class
 * May 2011
 * by Timothy Baldock <tb@entropy.me.uk>
 */

#include <string.h>
#include "fetchopt.h"

Fetchopt_t::Fetchopt_t(int argc, char **argv, const char *optstring) {
	optarg = NULL;
	optind = 1;
	optstr = optstring;
	ac = argc;
	av = argv;
	pos = 1;
}

char *Fetchopt_t::get_optarg() {
	return optarg;
}

int Fetchopt_t::get_optind() {
	return optind;
}

int Fetchopt_t::next() {
	optarg = NULL;
	if (optind >= ac || av[optind][0] != '-') {
		return -1;
	}
	int optchar = av[optind][pos];
	const char *offset = strchr(optstr, optchar);
	if (offset == NULL || optchar == ':') {
		// Invalid option
		return '?';
	}
	if (*(offset+1) == ':') {
		// Option with argument
		if (av[optind][pos+1] == '\0') {
			// Use next argument for option's argument
			if (ac < optind+2) {
				// Missing argument
				return '?';
			} else {
				optarg = av[optind+1];
				optind += 2;
			}
		} else {
			// Use rest of current argument for option's argument
			optarg = av[optind]+pos+1;
			optind++;
		}
		pos = 1;
		return optchar;
	} else {
		// Simple option
		pos++;
		if (av[optind][pos] == '\0') {
			// Next argument
			pos = 1;
			optind++;
		}
		return optchar;
	}
}