Example of getopt in C

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;
}

Download it here.

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.

Ask and answer questions on C in the new C forum

Copyright © Ben Bullock 2009-2012. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (ben.bullock@lemoda.net) / Privacy / Disclaimer