File: evalopt.c

package info (click to toggle)
fdclone 3.01b-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 4,772 kB
  • ctags: 8,674
  • sloc: ansic: 100,552; makefile: 4,497; sh: 1,480; sed: 224
file content (93 lines) | stat: -rw-r--r-- 1,691 bytes parent folder | download
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
 *	evalopt.c
 *
 *	option arguments parser
 */

#include "headers.h"
#include "evalopt.h"

static CONST opt_t *NEAR getoption __P_((int, CONST opt_t *));


static CONST opt_t *NEAR getoption(c, optlist)
int c;
CONST opt_t *optlist;
{
	int n;

	if (!optlist) return(NULL);
	for (n = 0; optlist[n].opt; n++)
		if (c == optlist[n].opt) return(&(optlist[n]));

	return(NULL);
}

VOID initopt(optlist)
CONST opt_t *optlist;
{
	int n;

	if (!optlist) return;
	for (n = 0; optlist[n].opt; n++)
		if (optlist[n].var) *(optlist[n].var) = 0;
}

VOID optusage(arg0, args, optlist)
CONST char *arg0, *args;
CONST opt_t *optlist;
{
	int n;

	fprintf(stderr, "Usage: %s", arg0);
	n = 0;
	if (optlist) while (optlist[n].opt) n++;
	if (n > 0) {
		fputs(" [-", stderr);
		for (n = 0; optlist[n].opt; n++) {
			fputc(optlist[n].opt, stderr);

			if (!(optlist[n].argval)) continue;
			fprintf(stderr, " <%s>", optlist[n].argval);
			if (optlist[n + 1].opt) fputs(" [-", stderr);
		}
		fputc(']', stderr);
	}
	fprintf(stderr, " %s\n", args);
}

int evalopt(argc, argv, optlist)
int argc;
char *CONST *argv;
CONST opt_t *optlist;
{
	CONST char *cp;
	CONST opt_t *optp;
	int i, n, val;

	for (n = 1; n < argc; n++) {
		if (argv[n][0] != '-' || !argv[n][1]) break;
		if (argv[n][1] == '=' && !argv[n][2]) {
			n++;
			break;
		}

		for (i = 1; argv[n][i]; i++) {
			if (!(optp = getoption(argv[n][i], optlist)))
				return(-1);

			if (!(optp -> argval)) {
				if (optp -> var) *(optp -> var) = optp -> val;
			}
			else {
				cp = &(argv[n][++i]);
				if (!*cp) cp = argv[++n];
				if (!cp || (val = atoi(cp)) <= 0) return(-1);
				if (optp -> var) *(optp -> var) = val;
				break;
			}
		}
	}

	return(n);
}