Update.
[glibc.git] / manual / examples / argp-ex3.c
blob363ee59e11d1a6e012855ad5bcb9cd7c1a9dfe11
1 /* Argp example #3 -- a program with options and arguments using argp */
3 #include <argp.h>
5 const char *argp_program_version =
6 "argp-ex3 1.0";
7 const char *argp_program_bug_address =
8 "<bug-gnu-utils@@prep.ai.mit.edu>";
10 /* Program documentation. */
11 static char doc[] =
12 "Argp example #3 -- a program with options and arguments using argp";
14 /* A description of the arguments we accept. */
15 static char args_doc[] = "ARG1 ARG2";
17 /* The options we understand. */
18 static struct argp_option options[] = {
19 {"verbose", 'v', 0, 0, "Produce verbose output" },
20 {"quiet", 'q', 0, 0, "Don't produce any output" },
21 {"silent", 's', 0, OPTION_ALIAS },
22 {"output", 'o', "FILE", 0,
23 "Output to FILE instead of standard output" },
24 { 0 }
27 /* Used by @code{main} to communicate with @code{parse_opt}. */
28 struct arguments
30 char *args[2]; /* @var{arg1} & @var{arg2} */
31 int silent, verbose;
32 char *output_file;
35 /* Parse a single option. */
36 static error_t
37 parse_opt (int key, char *arg, struct argp_state *state)
39 /* Get the @var{input} argument from @code{argp_parse}, which we
40 know is a pointer to our arguments structure. */
41 struct arguments *arguments = state->input;
43 switch (key)
45 case 'q': case 's':
46 arguments->silent = 1;
47 break;
48 case 'v':
49 arguments->verbose = 1;
50 break;
51 case 'o':
52 arguments->output_file = arg;
53 break;
55 case ARGP_KEY_ARG:
56 if (state->arg_num >= 2)
57 /* Too many arguments. */
58 argp_usage (state);
60 arguments->args[state->arg_num] = arg;
62 break;
64 case ARGP_KEY_END:
65 if (state->arg_num < 2)
66 /* Not enough arguments. */
67 argp_usage (state);
68 break;
70 default:
71 return ARGP_ERR_UNKNOWN;
73 return 0;
76 /* Our argp parser. */
77 static struct argp argp = { options, parse_opt, args_doc, doc };
79 int main (int argc, char **argv)
81 struct arguments arguments;
83 /* Default values. */
84 arguments.silent = 0;
85 arguments.verbose = 0;
86 arguments.output_file = "-";
88 /* Parse our arguments; every option seen by @code{parse_opt} will
89 be reflected in @code{arguments}. */
90 argp_parse (&argp, argc, argv, 0, 0, &arguments);
92 printf ("ARG1 = %s\nARG2 = %s\nOUTPUT_FILE = %s\n"
93 "VERBOSE = %s\nSILENT = %s\n",
94 arguments.args[0], arguments.args[1],
95 arguments.output_file,
96 arguments.verbose ? "yes" : "no",
97 arguments.silent ? "yes" : "no");
99 exit (0);