// ------- getopt_test.c beg --------- #include #include #include // Ref.: // Alp-ch02-writing-good-gnu-linux-software.pdf // Libc_25.html#SEC531 // // Compile it: // gcc -Wall getopt_test.c -o getopt_test // // Run it: // getopt_test -h // getopt_test --help void print_usage(char *program); // This becomes true ('v') if --verbose or -v option was seen. int verbose_flag = 0; // Optional value after -v or --verbose=. int verbose_level= 0; const struct option long_options[] = { {"verbose", optional_argument, &verbose_flag, 'v'}, {"help", no_argument, NULL, 'h'}, {"user", required_argument, NULL, 'u'}, {"password", required_argument, NULL, 'p'}, {NULL, 0, NULL, 0 } }; // u and p take values and v can optionally have a value. static const char *short_options = "v:hu:p:"; int main(int argc, char *argv[]) { int c; int option_index = 0; // Valid only for long_options (eg. --help). while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) { switch (c) { case 0: // --verbose if (long_options[option_index].val == 'v') { ; } if (optarg) verbose_level = atoi(optarg); break; case 'v': // -v verbose_flag = 'v'; // This is not set automatically. if (optarg) verbose_level = atoi(optarg); break; case 'h': // -h or --help printf("Help is here\n"); print_usage(argv[0]); break; case 'u': // -u or --user printf("User is %s\n", optarg); break; case 'p': // -p or --password printf("Password is %s\n", optarg); break; case '?': // Invalid argument print_usage(argv[0]), exit(-1); break; default: printf("Something went wrong.\n"); } } printf("Verbose_flag was set? %s. level %d\n",(verbose_flag == 'v' ? "Yes" : "No"), verbose_level); // Print rest of the arguments not caught by getopt_long(). if (optind < argc) { printf ("\nOther command line args:\n"); while (optind < argc) printf ("%s\n", argv[optind++]); } // Ok return 0; } void print_usage(char *program) { fprintf(stderr, "Usage: %s [options]\n%s\n%s\n%s\n%s\n", program, "-h or --help", "-v [optional level] or --verbose [=optional level]", "-u or --user=", "-p or --password="); } // ------- getopt_test.c end ---------