Fix a strict-alias warning in tst-inet6_rth.
[glibc.git] / manual / examples / longopt.c
blob6e7d4d939a51ea99c01c9fef83b0fcd8e217f625
1 /* Example of Parsing Long Options with getopt_long.
2 Copyright (C) 1991-2012 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <getopt.h>
22 /* Flag set by @samp{--verbose}. */
23 static int verbose_flag;
25 int
26 main (int argc, char **argv)
28 int c;
30 while (1)
32 static struct option long_options[] =
34 /* These options set a flag. */
35 {"verbose", no_argument, &verbose_flag, 1},
36 {"brief", no_argument, &verbose_flag, 0},
37 /* These options don't set a flag.
38 We distinguish them by their indices. */
39 {"add", no_argument, 0, 'a'},
40 {"append", no_argument, 0, 'b'},
41 {"delete", required_argument, 0, 'd'},
42 {"create", required_argument, 0, 'c'},
43 {"file", required_argument, 0, 'f'},
44 {0, 0, 0, 0}
46 /* @code{getopt_long} stores the option index here. */
47 int option_index = 0;
49 c = getopt_long (argc, argv, "abc:d:f:",
50 long_options, &option_index);
52 /* Detect the end of the options. */
53 if (c == -1)
54 break;
56 switch (c)
58 case 0:
59 /* If this option set a flag, do nothing else now. */
60 if (long_options[option_index].flag != 0)
61 break;
62 printf ("option %s", long_options[option_index].name);
63 if (optarg)
64 printf (" with arg %s", optarg);
65 printf ("\n");
66 break;
68 case 'a':
69 puts ("option -a\n");
70 break;
72 case 'b':
73 puts ("option -b\n");
74 break;
76 case 'c':
77 printf ("option -c with value `%s'\n", optarg);
78 break;
80 case 'd':
81 printf ("option -d with value `%s'\n", optarg);
82 break;
84 case 'f':
85 printf ("option -f with value `%s'\n", optarg);
86 break;
88 case '?':
89 /* @code{getopt_long} already printed an error message. */
90 break;
92 default:
93 abort ();
97 /* Instead of reporting @samp{--verbose}
98 and @samp{--brief} as they are encountered,
99 we report the final status resulting from them. */
100 if (verbose_flag)
101 puts ("verbose flag is set");
103 /* Print any remaining command line arguments (not options). */
104 if (optind < argc)
106 printf ("non-option ARGV-elements: ");
107 while (optind < argc)
108 printf ("%s ", argv[optind++]);
109 putchar ('\n');
112 exit (0);