]> Pileus Git - ~andy/sfvlug/blob - c/src/opts.c
Add C notes.
[~andy/sfvlug] / c / src / opts.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <getopt.h>
4
5 /* Options */
6 static int   opt_verbose  = 0;
7 static char *opt_greeting = "Hello";
8 static char *opt_name     = "World";
9
10 /* Parsing */
11 static char *short_options = "hvg:n:";
12
13 static struct option long_options[] = {
14         {"help",     0, NULL, 'h'},
15         {"verbose",  0, NULL, 'v'},
16         {"greeting", 1, NULL, 'g'},
17         {"name",     1, NULL, 'n'},
18 };
19
20 /* Show usage information */
21 static void usage(int status)
22 {
23         printf("opts -[OPTIONS]\n");
24         printf("\n");
25         printf("Options:\n");
26         printf("  -h,--help          Show usage information\n");
27         printf("  -v,--verbose       Print debug output messages\n");
28         printf("  -n,--greeting=STR  Use the given greeting\n");
29         printf("  -n,--name=NAME     Greet the given person\n");
30         exit(status);
31 }
32
33 /* Parse command line arguments */
34 static void parse(int argc, char **argv)
35 {
36         while (1) {
37                 int c = getopt_long(argc, argv,
38                                 short_options, long_options, 0);
39                 if (c == -1)
40                         break;
41                 switch (c) {
42                         case 'h': usage(0);               break;
43                         case 'v': opt_verbose   = 1;      break;
44                         case 'g': opt_greeting  = optarg; break;
45                         case 'n': opt_name      = optarg; break;
46                         default:  usage(1);               break;
47                 }
48         }
49         if (argc != optind)
50                 usage(1);
51
52         if (opt_verbose) {
53                 printf("Options:\n");
54                 printf("  verbose  = %d\n", opt_verbose);
55                 printf("  greeting = %s\n", opt_greeting);
56                 printf("  name     = %s\n", opt_name);
57                 printf("\n");
58         }
59 }
60
61 /* Main entry point */
62 int main(int argc, char **argv)
63 {
64         parse(argc, argv);
65         printf("%s, %s\n", opt_greeting, opt_name);
66         return 0;
67 }