A small, C99, single-header, zero-allocation, dependency-free, public domain argument parsing library
Find a file
Lukas Wurzinger b4b72a51d5 replace READOPT_ALLOC_STRINGS with READOPT_STRINGS
The word "alloc" could be misleading in this context.
2022-09-30 16:34:08 +02:00
test replace READOPT_ALLOC_STRINGS with READOPT_STRINGS 2022-09-30 16:34:08 +02:00
.clang-format formatting 2022-09-25 12:08:56 +02:00
.gitignore turn readopt into a single-header library 2022-09-25 12:40:12 +02:00
LICENSE relicense to CC0 2022-09-25 12:43:36 +02:00
README.md update readme 2022-09-29 21:33:41 +02:00
readopt.h replace READOPT_ALLOC_STRINGS with READOPT_STRINGS 2022-09-30 16:34:08 +02:00

readopt

Features

  • Short options (-f)
    • Short options with a value directly following the option character (-fvalue)
    • Short options with a value as a separate argv element (-f value)
    • Grouped short options (-asdf, -asdfvalue, -asdf value)
  • Long options (--file)
    • Long options with a value separated by an equal sign (--file=value)
    • Long options with a value as a separate argv element (--file value)
  • Multiple values are represented in an array (-f value1 -f value2 ...)
  • Operands mixed with options (-f value1 operand1 -f value2 operand2)

Usage

Installing this library is as simple as downloading the header file, dropping it into your project directory and including it. Alternatively, you could choose to use a Git submodule. In any case, attribution is not required.

It is required that one file in your project defines the READOPT_IMPLEMENTATION macro before including the readopt.h header file, as with any other single-header library.

An example for how to use readopt can be found in test/test.c. If you want to see how readopt represents options and operands, execute test.sh in the same directory.

Terminology

If you're wondering what exactly the difference between an option, an operand or an argument is, you can skim this document to get a better idea: POSIX Utility Conventions

Internals

readopt permutes argv to handle multiple values for each option and to assign values to operands. The advantage of this approach is as follows:

  • Allocations are not needed because the memory provided by argv is reused
  • It's fairly simple to represent all of this data in an intuitive data structure (in my opinion anyway)
    • For example, looping through operands is as simple as incrementing parser.oper until readopt_validate_oper returns 0.