modified: src1/input.c
[GalaxyCodeBases.git] / c_cpp / lib / klib / test / ketopt_test.c
blob4009e246af877784ddb2b676393ef8d5a5816e06
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <getopt.h>
4 #include "ketopt.h"
6 static void test_opt(int c, int opt, const char *arg)
8 if (c == 'x') fprintf(stderr, "-x\n");
9 else if (c == 'y') fprintf(stderr, "-y %s\n", arg);
10 else if (c == 301) fprintf(stderr, "--foo\n");
11 else if (c == 302) fprintf(stderr, "--bar %s\n", arg? arg : "(null)");
12 else if (c == 303) fprintf(stderr, "--opt %s\n", arg? arg : "(null)");
13 else if (c == '?') fprintf(stderr, "unknown option -%c\n", opt? opt : ':');
14 else if (c == ':') fprintf(stderr, "missing option argument: -%c\n", opt? opt : ':');
17 static void print_cmd(int argc, char *argv[], int ind)
19 int i;
20 fprintf(stderr, "CMD: %s", argv[0]);
21 if (ind > 1) {
22 fputs(" [", stderr);
23 for (i = 1; i < ind; ++i) {
24 if (i != 1) fputc(' ', stderr);
25 fputs(argv[i], stderr);
27 fputc(']', stderr);
29 for (i = ind; i < argc; ++i)
30 fprintf(stderr, " %s", argv[i]);
31 fputc('\n', stderr);
34 static void test_ketopt(int argc, char *argv[])
36 static ko_longopt_t longopts[] = {
37 { "foo", ko_no_argument, 301 },
38 { "bar", ko_required_argument, 302 },
39 { "opt", ko_optional_argument, 303 },
40 { NULL, 0, 0 }
42 ketopt_t opt = KETOPT_INIT;
43 int c;
44 fprintf(stderr, "===> ketopt() <===\n");
45 while ((c = ketopt(&opt, argc, argv, 1, "xy:", longopts)) >= 0)
46 test_opt(c, opt.opt, opt.arg);
47 print_cmd(argc, argv, opt.ind);
50 static void test_getopt(int argc, char *argv[])
52 static struct option long_options[] = {
53 { "foo", no_argument, 0, 301 },
54 { "bar", required_argument, 0, 302 },
55 { "opt", optional_argument, 0, 303 },
56 {0, 0, 0, 0}
58 int c, option_index;
59 fprintf(stderr, "===> getopt() <===\n");
60 while ((c = getopt_long(argc, argv, ":xy:", long_options, &option_index)) >= 0)
61 test_opt(c, optopt, optarg);
62 print_cmd(argc, argv, optind);
65 int main(int argc, char *argv[])
67 int i;
68 char **argv2;
69 if (argc == 1) {
70 fprintf(stderr, "Usage: ketopt_test [options] <argument> [...]\n");
71 fprintf(stderr, "Options:\n");
72 fprintf(stderr, " -x no argument\n");
73 fprintf(stderr, " -y STR required argument\n");
74 fprintf(stderr, " --foo no argument\n");
75 fprintf(stderr, " --bar=STR required argument\n");
76 fprintf(stderr, " --opt[=STR] optional argument\n");
77 fprintf(stderr, "\nExamples:\n");
78 fprintf(stderr, " ketopt_test -xy1 -x arg1 -y -x -- arg2 -x\n");
79 fprintf(stderr, " ketopt_test --foo --bar=1 --bar 2 --opt arg1 --opt=3\n");
80 fprintf(stderr, " ketopt_test arg1 -y\n");
81 return 1;
83 argv2 = (char**)malloc(sizeof(char*) * argc);
84 for (i = 0; i < argc; ++i) argv2[i] = argv[i];
85 test_ketopt(argc, argv);
86 test_getopt(argc, argv2);
87 free(argv2);
88 return 0;