Skip to content

Instantly share code, notes, and snippets.

@TruncatedDinoSour
Last active April 7, 2024 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TruncatedDinoSour/115550bd8e714a15c965339b8ae4ce84 to your computer and use it in GitHub Desktop.
Save TruncatedDinoSour/115550bd8e714a15c965339b8ae4ce84 to your computer and use it in GitHub Desktop.
Simple CLI flag parsing in C
/*
UNLICENSE
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "cli.h"
unsigned char cli_parse_flags(CliFlag flags[],
const size_t flags_size,
char *argv[],
const size_t argv_size) {
char *arg;
CliFlag *flag;
size_t idx, jdx;
for (idx = 0; idx < flags_size; ++idx) {
flag = &flags[idx];
if (*flag->flag != '-')
continue;
for (jdx = 0; jdx < argv_size; ++jdx) {
arg = argv[jdx];
if (*arg != '-' || strcmp(flag->flag, arg) != 0)
continue;
if (flag->as_switch)
flag->value = argv[jdx];
else if (++jdx == argv_size)
break;
flag->value = argv[jdx];
}
if (flag->required && flag->value == NULL)
return 0;
}
return 1;
}
void cli_print_flags(FILE *fp,
const CliFlag flags[],
const size_t flags_size,
const unsigned char only_required) {
size_t idx;
for (idx = 0; idx < flags_size; ++idx) {
if (only_required &&
(!flags[idx].required || flags[idx].value != NULL)) {
continue;
}
fprintf(fp, "%s%s%s - %s\n", flags[idx].flag,
flags[idx].as_switch ? "" : " <value>",
flags[idx].required ? " (required)" : "",
flags[idx].description);
}
}
/*
UNLICENSE
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
#ifndef _CLI_H
#define _CLI_H
#include <stddef.h>
#include <stdio.h>
#define cli_flags(flags) flags, (sizeof(flags) / sizeof(flags[0]))
#define cli_argv(argv, argc) (char **)((argv) + 1), (size_t)((argc)-1)
#define cli_flag(flag, description, as_switch, required) \
{ (flag), (description), (as_switch), (required), NULL }
typedef struct {
const char *const flag;
const char *const description;
const unsigned char as_switch;
const unsigned char required;
char *value;
} CliFlag;
unsigned char cli_parse_flags(CliFlag flags[],
const size_t flags_size,
char *argv[],
const size_t argv_size);
void cli_print_flags(FILE *fp, const CliFlag flags[], const size_t flags_size, const unsigned char only_required);
#endif /* _CLI_H */
/*
UNLICENSE
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
#include <stdio.h>
#include "main.h"
#include "cli.h"
int main(const int argc, char *argv[]) {
size_t idx;
CliFlag flags[] = {
cli_flag("-hello", "The hello flag", 0, 0),
cli_flag("-world", "The REQUIRED world flag", 0, 1),
cli_flag("-yeah", "A boolean flag", 1, 0),
cli_flag("-run", "A REQUIRED boolean flag", 1, 1),
cli_flag("-help", "Print help", 1, 0),
};
if (!cli_parse_flags(cli_flags(flags), cli_argv(argv, argc))) {
puts("Required flags not specified:");
cli_print_flags(stdout, cli_flags(flags), 1);
return 1;
}
if (flags[4].value != NULL) {
cli_print_flags(stdout, cli_flags(flags), 0);
puts("");
}
puts("Flag values:");
for (idx = 0; idx < sizeof(flags) / sizeof(flags[0]); ++idx)
printf("%s = %s\n", flags[idx].flag,
flags[idx].as_switch
? (flags[idx].value == NULL ? "false" : "true")
: flags[idx].value);
return 0;
}
/*
UNLICENSE
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
#ifndef _MAIN_H
#define _MAIN_H
int main(const int, char *[]);
#endif /* _MAIN_H */
@TruncatedDinoSour
Copy link
Author

you can use enums for indexing the flags, also you can add status codes instead of just 'success' and 'failure'

@TruncatedDinoSour
Copy link
Author

TruncatedDinoSour commented Apr 7, 2024

also more example usage in https://ari.lt/gh/kos :

#include <stdio.h>

#include "main.h"
#include "cli.h"

#define VERSION "44"

enum AppFlag { AppFlag_help = 0, AppFlag_count };

static CliFlag flags[AppFlag_count] = {
    /* If you are not using C89: [AppFlag_help] = */ {"-help", "Print the help page", 1, 0, NULL},
};

static void print_help(FILE *fp) {
    fputs("Kos version " VERSION "\nUsage: kos [flags] <command...>\n\n",
          stderr);
    cli_print_flags(fp, cli_flags(flags), 0);
}

int main(const int argc, char *argv[]) {
    if (argc < 2) {
        print_help(stderr);
        return 1;
    }

    if (!cli_parse_flags(cli_flags(flags), cli_argv(argv, argc))) {
        fputs("Flag parsing error. Are you sur4e you specified the "
              "(required) flags?\n\n",
              stderr);
        print_help(stderr);
        return 1;
    }

    if (flags[AppFlag_help].value != NULL) {
        print_help(stdout);
        return 0;
    }

    return 0;
}

@TruncatedDinoSour
Copy link
Author

to make it clear : use this code however you want, any license, no need for credit or anything

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment