OMKOV Argument Parser
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Jake Wakeling 88113f4275 Make opt_t and lop_t str members const for C++ 2 months ago
include Make opt_t and lop_t str members const for C++ 2 months ago
man Add improved description to README 3 months ago
test Fix long option segfault when lopts unset 3 months ago
LICENCE Add LICENCE and README 4 months ago
README.md Add improved description to README 3 months ago

README.md

optget

OMKOV Argument Parser

optget is a portable, minimal, and fast argument parser. It supports argument permutation, compact option-arguments, multiple option occurrances, option order, and long options.

Synopsys

#include <optget.h>

int optget(opt_t *opt, char *argv[], int flags);

Usage

To use optget(), at program start, an opt_t struct should be created and initialised to OPTGET_INIT, the fields str and lops should then be initialised. lops may be left uninitialised if long options are not required.

A pointer to this opt_t struct, along argv and flags should then be passed to the optget() function in a loop. Each time the loop runs the next option will be parsed.

Each time optget() is called, it will return the next option character or, for a long option, val.

See the manpage and examples for a more cohesive description.

Examples

Short options only

#include <optget.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    opt_t opt = OPTGET_INIT; opt.str = ":ab:"; int o;
    while ((o = optget(&opt, argv, 1)) != -1) switch (o) {
    case 'a': { printf("-a\n"); break; }
    case 'b': { printf("-b: %s\n", opt.arg); break; }
    case '?': { printf("invalid option -- '%c'\n", opt.opt); break; }
    case ':': { printf("missing argument -- '%c'\n", opt.opt); break; }
    }

    puts("non-option arguments:");
    for (int i = opt.ind; i < argc; ++i) { printf("%s\n", argv[i]); }

    return 0;
}

Short and long options

#include <optget.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    lop_t lops[] = {
        { "bee", ARG_REQ, 'b' },
        { "foo", ARG_NUL, 256 },
        { "bar", ARG_REQ, 257 },
        { "baz", ARG_OPT, 258 },
        { NULL, 0, 0 }
    };

    opt_t opt = OPTGET_INIT; int o;
    opt.str = "ab:"; opt.lops = lops;
    while ((o = optget(&opt, argv, 1)) != -1) switch (o) {
    case 'a': { printf("-a\n"); break; }
    case 'b': { printf("-b/--bee: %s\n", opt.arg); break; }
    case 256: { printf("--foo\n"); break; }
    case 257: { printf("--bar: %s\n", opt.arg); break; }
    case 258: { printf("--baz: %s\n", opt.arg); break; }
    default: { break; }
    }

    puts("non-option arguments:");
    for (int i = opt.ind; i < argc; ++i) { printf("%s\n", argv[i]); }

    return 0;
}

Meta

Copyright (C) 2020, Jakob Wakeling
All rights reserved.
OMKOV Permissive Licence