From 98ab1d968030494fbfbe3688929b761382b28b09 Mon Sep 17 00:00:00 2001 From: Juan Manuel Tomas Date: Thu, 5 Aug 2021 01:18:19 -0300 Subject: Initial Commit --- README.md | 8 ++++++++ flag.h | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ test/main.c | 8 ++++++++ 3 files changed, 73 insertions(+) create mode 100644 README.md create mode 100644 flag.h create mode 100644 test/main.c diff --git a/README.md b/README.md new file mode 100644 index 0000000..13f442a --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +* Shady Flag Library + +This is a library for parsing command line flags. +Just include the .h file and you're good to go. +Example: +```int hello = flag_int("--testing", 420, " Hello World");``` +This will put on the variable hello the value following the --testing command +line flag, or the default value 420 if the flag is not present. diff --git a/flag.h b/flag.h new file mode 100644 index 0000000..3601d01 --- /dev/null +++ b/flag.h @@ -0,0 +1,57 @@ +#include +#include +#include + +#define flag_init main + +int argument_count; +char **arguments; +int docstring_count; +char **docstrings; +int flag_fail; + +int flag_int(const char *flag_name, int default_value, const char *docstring) { + int flag_name_length = strlen(flag_name); + int docstring_length = strlen(docstring); + char *new_docstring = malloc(flag_name_length + 4 + docstring_length); + new_docstring[0] = '\t'; + memcpy(new_docstring + 1, flag_name, flag_name_length); + new_docstring[flag_name_length + 1] = ' '; + memcpy(new_docstring + flag_name_length + 2, docstring, docstring_length); + new_docstring[flag_name_length + 3 + docstring_length] = '\0'; + docstrings[docstring_count] = new_docstring; + docstring_count++; + for (int i = 0; i < argument_count; i++) { + if (strcmp(arguments[i], flag_name) == 0) { + if (i + 1 < argument_count) { + return atoi(arguments[i + 1]); + } else { + flag_fail = 1; + } + } + } + if (flag_fail) { + printf("Usage: %s [flags]\n", arguments[0]); + puts("Available flags:"); + for (int j = 0; j < docstring_count; j++) { + printf("%s\n", docstrings[j]); + } + exit(1); + return 0; + } else { + return default_value; + } +} + +int main_func(); + +int flag_init(int argc, char **argv) { + argument_count = argc; + arguments = argv; + flag_fail = 0; + docstring_count = 0; + docstrings = malloc(argc * sizeof(char *)); + main_func(argc, argv); +} + +#define main main_func diff --git a/test/main.c b/test/main.c new file mode 100644 index 0000000..3b6c977 --- /dev/null +++ b/test/main.c @@ -0,0 +1,8 @@ +#include +#include "../flag.h" + +int main() { + int test1 = flag_int("-j", 69, " Specifies the number of cores to be used."); + printf("This is the first test argument: %d\n", test1); + return 0; +} -- cgit v1.2.3