* elf/dl-error.c (_dl_catch_error): Use __sigsetgjmp instead of
[glibc.git] / manual / examples / longopt.c
blob1661327f53bb721ec54ddea5e96794f1dd4c2525
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", no_argument, &verbose_flag, 1},
21 {"brief", no_argument, &verbose_flag, 0},
22 /* These options don't set a flag.
23 We distinguish them by their indices. */
24 {"add", no_argument, 0, 'a'},
25 {"append", no_argument, 0, 'b'},
26 {"delete", required_argument, 0, 'd'},
27 {"create", required_argument, 0, 'c'},
28 {"file", required_argument, 0, 'f'},
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:f:",
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 'f':
70 printf ("option -f with value `%s'\n", optarg);
71 break;
73 case '?':
74 /* @code{getopt_long} already printed an error message. */
75 break;
77 default:
78 abort ();
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");
88 /* Print any remaining command line arguments (not options). */
89 if (optind < argc)
91 printf ("non-option ARGV-elements: ");
92 while (optind < argc)
93 printf ("%s ", argv[optind++]);
94 putchar ('\n');
97 exit (0);