getopt.c

DownloadView Raw

/**
 * getopt.c
 *
 * Demonstrates using the getopt() function to parse command line options.
 *
 */

#include <errno.h>
#include <stdio.h>
#include <string.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 has_operation = false;

    int c;
    opterr = 0;
    while ((c = getopt(argc, argv, "asmdh")) != -1) {
        switch (c) {
            case 'a':
                if (has_operation) {
                    /* angrily tell the user to stop! */
                }
                has_operation = true;
                break;
            case 's':
                str_option = optarg;
                break;
            case '?':
                if (optopt == 's') {
                    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 c_flag = %s, str_option = %s\n",
            c_flag ? "true" : "false",
            str_option);

    int i;
    for (i = optind; i < argc; i++) {
        printf("Non-option argument %s\n", argv[i]);
    }

    return 0;
}