This is an example C program for getopt.
#include <stdio.h> /* getopt is defined in "unistd.h". */ #include <unistd.h> int main (int argc, char ** argv) { while (1) { char c; c = getopt (argc, argv, "ab:"); if (c == -1) { break; } switch (c) { case 'a': printf ("User has invoked with -a.\n"); break; case 'b': printf ("User has invoked with -b %s.\n", optarg); break; case '?': default: printf ("Usage: %s [-a] [-b <something>].\n", argv[0]); } } return 0; }
The output of the example looks like this:
$ ./getopt $ ./getopt -a User has invoked with -a. $ ./getopt -b getopt: option requires an argument -- b Usage: ./getopt [-a] [-b]. $ ./getopt -b something User has invoked with -b something.