getopt
The snippet can be accessed without any authentication.
Authored by
Stephan Boekelmann
This program demonstrates a simple usage of getopt to parse two options: -h and -v. If the user runs the program with the -h option, it prints a help message and exits. If the -v option is used, it sets a verbosity flag to 1 (true), indicating that verbose mode is on, and then it prints a message indicating whether verbose mode is activated.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
int verbose = 0;
while ((opt = getopt(argc, argv, "hv")) != -1) {
switch (opt) {
case 'h':
printf("Usage: %s [-h] [-v]\n", argv[0]);
printf(" -h Display this help and exit\n");
printf(" -v Increase verbosity\n");
exit(EXIT_SUCCESS);
case 'v':
verbose = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-h] [-v]\n", argv[0]);
exit(EXIT_FAILURE);
}
}
if (verbose) {
printf("Verbose mode is on.\n");
} else {
printf("Verbose mode is off.\n");
}
// Your program's logic goes here
return EXIT_SUCCESS;
}
Please register or sign in to comment