getopt.c
/**
* getopt.c
*
* Demonstrates using the getopt() function to parse command line options.
*
* Try running this with a combination of command line options, e.g.:
* cc -Wall getopt.c -o getopt
*
* ./getopt -a test1 test2
* ./getopt -s 'different string' test1 test2
* ./getopt -s hi -a testing 1 2 3
*
* And observe the behavior.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
char *str_option = "default string";
bool some_boolean = false;
int c;
opterr = 0;
// notice how we support 'a' and 's' options, and -s requires an argument so
// it has a trailing colon character ':'
while ((c = getopt(argc, argv, "as:")) != -1) {
switch (c) {
case 'a':
// the -a flag will turn on some_boolean
some_boolean = true;
break;
case 's':
// the -s flag will change what str_option points at. Notice how
// we use 'optarg' to get whatever came after -s, e.g., if the
// command line included -s test then optarg points at 'test'.
str_option = optarg;
break;
case '?':
if (optopt == 's') {
// if -s was passed with no argument, that's a problem.
fprintf(stderr,
"Option -%c requires an argument.\n", optopt);
} else if (isprint(optopt)) {
fprintf(stderr, "Unknown option '-%c'.\n", optopt);
} else {
fprintf(stderr,
"Unknown option character `\\x%x'.\n", optopt);
}
return 1;
default:
abort();
}
}
printf("Done parsing options. some_boolean = %s, str_option = %s\n",
some_boolean ? "true" : "false",
str_option);
// 'optind' is the beginning of the non-option command line arguments.
for (int i = optind; i < argc; i++) {
printf("Non-option argument %s\n", argv[i]);
}
return 0;
}