]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/examples/longopt.c
Update.
[thirdparty/glibc.git] / manual / examples / longopt.c
CommitLineData
28f540f4 1#include <stdio.h>
46d9215f
RM
2#include <stdlib.h>
3#include <getopt.h>
28f540f4
RM
4
5/* Flag set by @samp{--verbose}. */
6static int verbose_flag;
7
8int
9main (argc, argv)
10 int argc;
11 char **argv;
12{
13 int c;
14
15 while (1)
16 {
17 static struct option long_options[] =
18 {
19 /* These options set a flag. */
9495793d
UD
20 {"verbose", no_argument, &verbose_flag, 1},
21 {"brief", no_argument, &verbose_flag, 0},
28f540f4
RM
22 /* These options don't set a flag.
23 We distinguish them by their indices. */
9495793d
UD
24 {"add", required_argument, 0, 'a'},
25 {"append", no_argument, 0, 'b'},
26 {"delete", required_argument, 0, 'd'},
27 {"create", no_argument, 0, 'c'},
28 {"file", required_argument, 0, 'f'},
28f540f4
RM
29 {0, 0, 0, 0}
30 };
31 /* @code{getopt_long} stores the option index here. */
32 int option_index = 0;
33
9495793d 34 c = getopt_long (argc, argv, "abc:d:f:",
28f540f4
RM
35 long_options, &option_index);
36
37 /* Detect the end of the options. */
38 if (c == -1)
39 break;
40
41 switch (c)
42 {
43 case 0:
44 /* If this option set a flag, do nothing else now. */
45 if (long_options[option_index].flag != 0)
46 break;
47 printf ("option %s", long_options[option_index].name);
48 if (optarg)
49 printf (" with arg %s", optarg);
50 printf ("\n");
51 break;
52
53 case 'a':
54 puts ("option -a\n");
55 break;
56
57 case 'b':
58 puts ("option -b\n");
59 break;
60
61 case 'c':
62 printf ("option -c with value `%s'\n", optarg);
63 break;
64
65 case 'd':
66 printf ("option -d with value `%s'\n", optarg);
67 break;
68
9495793d
UD
69 case 'f':
70 printf ("option -f with value `%s'\n", optarg);
71 break;
72
28f540f4
RM
73 case '?':
74 /* @code{getopt_long} already printed an error message. */
75 break;
76
77 default:
78 abort ();
79 }
80 }
81
82 /* Instead of reporting @samp{--verbose}
83 and @samp{--brief} as they are encountered,
84 we report the final status resulting from them. */
85 if (verbose_flag)
86 puts ("verbose flag is set");
87
88 /* Print any remaining command line arguments (not options). */
89 if (optind < argc)
90 {
91 printf ("non-option ARGV-elements: ");
92 while (optind < argc)
93 printf ("%s ", argv[optind++]);
94 putchar ('\n');
95 }
96
97 exit (0);
98}