From cb953cc3f2d0f7ee44474913e2ce17fbfb787eb5 Mon Sep 17 00:00:00 2001 From: AUnicornWithNoLife <55228370+AUnicornWithNoLife@users.noreply.github.com> Date: Sat, 29 Jul 2023 13:23:01 +0100 Subject: [PATCH] added support for --flags --- carg-parse.c | 53 +++++++++++++++++++++++++++++++++++++++------------- carg-parse.h | 5 ++++- test.c | 7 +++++++ 3 files changed, 51 insertions(+), 14 deletions(-) diff --git a/carg-parse.c b/carg-parse.c index b42b8da..5848a55 100644 --- a/carg-parse.c +++ b/carg-parse.c @@ -14,26 +14,38 @@ carg_parse_data* carg_parse(int argc, char** argv) char **lv_values = (char**)malloc(sizeof(char*) * argc); uint32_t lv_cp = 0; + char **flags = (char**)malloc(sizeof(char*) * argc); + uint32_t flags_cp = 0; + data->exec_name = argv[0]; for (int i = 1; i < argc; i++) { - if (argv[i][0] == '-') // label + if (argv[i][0] == '-') // label / flag { - lv_labels[lv_cp] = argv[i] + 1; + if (argv[i][1] != '\0' && argv[i][1] == '-') // flag + { + flags[flags_cp] = argv[i] + 2; - if (argc > i + 1 && argv[i + 1][0] != '-') - { - i++; + flags_cp++; + } + else // label + { + lv_labels[lv_cp] = argv[i] + 1; - lv_values[lv_cp] = argv[i]; - } - else - { - lv_values[lv_cp] = NULL; - } + if (argc > i + 1 && argv[i + 1][0] != '-') + { + i++; - lv_cp++; + lv_values[lv_cp] = argv[i]; + } + else + { + lv_values[lv_cp] = NULL; + } + + lv_cp++; + } } else // not labelled { @@ -65,6 +77,16 @@ carg_parse_data* carg_parse(int argc, char** argv) data->lv_values = NULL; } + data->flags_len = flags_cp; + if (flags_cp > 0) + { + data->flags = realloc(flags, sizeof(char*) * flags_cp); + } + else + { + data->flags = NULL; + } + return data; } @@ -83,6 +105,11 @@ void carg_parse_free(carg_parse_data* data) { free(data->lv_values); } + + if (data->flags != NULL) + { + free(data->flags); + } free(data); -} \ No newline at end of file +} diff --git a/carg-parse.h b/carg-parse.h index 072f745..9acd9b8 100644 --- a/carg-parse.h +++ b/carg-parse.h @@ -15,9 +15,12 @@ typedef struct uint32_t lv_len; char** lv_labels; char** lv_values; + + uint32_t flags_len; + char** flags; } carg_parse_data; carg_parse_data* carg_parse(int argc, char** argv); void carg_parse_free(carg_parse_data* data); -#endif \ No newline at end of file +#endif diff --git a/test.c b/test.c index 6f4b590..46b87ae 100755 --- a/test.c +++ b/test.c @@ -30,6 +30,13 @@ int main(int argc, char** argv) } } + printf("\nFLAGS:\n"); + + for (uint32_t i = 0; i < data->flags_len; i++) + { + printf("%d :-: %s\n", i, data->flags[i]); + } + carg_parse_free(data); return 0;