summaryrefslogtreecommitdiffstats
path: root/usr/klibc/tests/getoptlong.c
blob: 6c019b7e438c1c448cdc5d6209a4249a433966e8 (plain)
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
/*
 * getoptlong.c
 *
 * Simple test for getopt_long, set the environment variable GETOPTTEST
 * to give the argument string to getopt()
 */

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>

static int foo = 0;

static const struct option long_options[] = {
	{ "first",   1, NULL, 'f' },
	{ "second",  0, NULL, 's' },
	{ "third",   2, NULL, '3' },
	{ "fourth",  0, NULL,  4 },
	{ "set-foo", 0, &foo,  1 },
	{ NULL, 0, NULL, 0 }
};

int main(int argc, char *const *argv)
{
	const char *parser;
	const char *showchar;
	char one_char[] = "\'?\'";
	char num_buf[16];
	int c;
	int longindex;

	parser = getenv("GETOPTTEST");
	if (!parser)
		parser = "abzf:o:";

	do {
		c = getopt_long(argc, argv, parser, long_options, &longindex);

		if (c == EOF) {
			showchar = "EOF";
		} else if (c >= 32 && c <= 126) {
			one_char[1] = c;
			showchar = one_char;
		} else {
			snprintf(num_buf, sizeof num_buf, "%d", c);
			showchar = num_buf;
		}

		printf("c = %s, optind = %d (\"%s\"), optarg = \"%s\", "
		       "optopt = \'%c\', foo = %d, longindex = %d\n",
		       showchar, optind, argv[optind],
		       optarg, optopt, foo, longindex);
	} while (c != -1);

	return 0;
}