Update.
[glibc.git] / manual / examples / longopt.c
blob9d6bd53c0f20639a1d7773fcff714af84c9af597
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <getopt.h>
5 /* Flag set by @samp{--verbose}. */
6 static int verbose_flag;
8 int
9 main (argc, argv)
10 int argc;
11 char **argv;
13 int c;
15 while (1)
17 static struct option long_options[] =
19 /* These options set a flag. */
20 {"verbose", 0, &verbose_flag, 1},
21 {"brief", 0, &verbose_flag, 0},
22 /* These options don't set a flag.
23 We distinguish them by their indices. */
24 {"add", 1, 0, 0},
25 {"append", 0, 0, 0},
26 {"delete", 1, 0, 0},
27 {"create", 0, 0, 0},
28 {"file", 1, 0, 0},
29 {0, 0, 0, 0}
31 /* @code{getopt_long} stores the option index here. */
32 int option_index = 0;
34 c = getopt_long (argc, argv, "abc:d:",
35 long_options, &option_index);
37 /* Detect the end of the options. */
38 if (c == -1)
39 break;
41 switch (c)
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;
53 case 'a':
54 puts ("option -a\n");
55 break;
57 case 'b':
58 puts ("option -b\n");
59 break;
61 case 'c':
62 printf ("option -c with value `%s'\n", optarg);
63 break;
65 case 'd':
66 printf ("option -d with value `%s'\n", optarg);
67 break;
69 case '?':
70 /* @code{getopt_long} already printed an error message. */
71 break;
73 default:
74 abort ();
78 /* Instead of reporting @samp{--verbose}
79 and @samp{--brief} as they are encountered,
80 we report the final status resulting from them. */
81 if (verbose_flag)
82 puts ("verbose flag is set");
84 /* Print any remaining command line arguments (not options). */
85 if (optind < argc)
87 printf ("non-option ARGV-elements: ");
88 while (optind < argc)
89 printf ("%s ", argv[optind++]);
90 putchar ('\n');
93 exit (0);