Site Tools


wiki:h-getopt

Table of Contents

<getopt.h>

<getopt.h> (POSIX/GNU) provides getopt for short options (-v, -o file) and getopt_long for long options (--verbose, --output=file). It handles argument parsing, optarg tracking, and stops at the first non-option argument or --.

Use it to parse command-line arguments portably instead of handling argv manually.

Example

This example parses both short and long options, handling argument requirements.

// compile: gcc -o getoptexample getoptexample.c
// run: ./getoptexample -v --output=out.txt file1.txt
// description: parse short and long options with arguments
 
#include <getopt.h>
#include <stdio.h>
 
int main(int argc, char* argv[]) {
    int verbose = 0;
    const char* outfile = "a.out";
    int c;
 
    struct option opts[] = {
        {"verbose", no_argument, NULL, 'v'},
        {"output", required_argument, NULL, 'o'},
        {0, 0, 0, 0}
    };
 
    while ((c = getopt_long(argc, argv, "vo:", opts, NULL)) != -1) {
        switch (c) {
        case 'v': verbose = 1; break;
        case 'o': outfile = optarg; break;
        case '?': return 1;
        }
    }
 
    printf("verbose=%d output=%s\n", verbose, outfile);
    for (int i = optind; i < argc; i++)
        printf("  input: %s\n", argv[i]);
 
    return 0;
}
wiki/h-getopt.md · Last modified: by 127.0.0.1