Example of getopt in C

This is an example C program which illustrates the use of getopt.

#include <stdio.h>
/* getopt is defined in "unistd.h". */
#include <unistd.h>

int main (int argc, char ** argv)
    int i;

    while (1) {
        char c;

        c = getopt (argc, argv, "ab:");
        if (c == -1) {
            /* We have finished processing all the arguments. */
        switch (c) {
        case 'a':
            printf ("User has invoked with -a.\n");
        case 'b':
            printf ("User has invoked with -b %s.\n", optarg);
        case '?':
            printf ("Usage: %s [-a] [-b <something>].\n", argv[0]);

    /* Now set the values of "argc" and "argv" to the values after the
       options have been processed, above. */
    argc -= optind;
    argv += optind;

    /* Now do something with the remaining command-line arguments, if
       necessary. */
    if (argc > 0) {
        printf ("There are %d command-line arguments left to process:\n", argc);
        for (i = 0; i < argc; i++) {
            printf ("    Argument %d: '%s'\n", i + 1, argv[i]);
    return 0;


The output of the example looks like this:

User has invoked with -a.
getopt: option requires an argument -- b
Usage: ./getopt [-a] [-b <something>].
User has invoked with -b something.
User has invoked with -b something.
There are 2 command-line arguments left to process:
    Argument 1: 'another'
    Argument 2: 'thing'

The following Perl script runs the program to produce the output:

use warnings;
use strict;
my $file = 'getopt';
if (! -f $file) {
    system ("make getopt");
my @tests = (
    '-b something',
    '-b something another thing',

for my $test (@tests) {
    system ("./getopt $test");


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer