From 7cb6f902b6e8913ad4cf5a0e5be757d3b752c22c Mon Sep 17 00:00:00 2001 From: bjt-user Date: Tue, 22 Aug 2023 00:12:30 +0200 Subject: [PATCH] added cli parsing functions --- makefile | 8 ++++++++ src/cli_arg_parsing.c | 41 +++++++++++++++++++++++++++++++++++++++++ src/cli_arg_parsing.h | 5 +++++ src/main.c | 17 +++++------------ 4 files changed, 59 insertions(+), 12 deletions(-) create mode 100644 src/cli_arg_parsing.c create mode 100644 src/cli_arg_parsing.h diff --git a/makefile b/makefile index 2813953..dc2b1e2 100644 --- a/makefile +++ b/makefile @@ -22,3 +22,11 @@ clean: .PHONY: uninstall uninstall: rm /usr/local/bin/ics_analyzer + +.PHONY: test +test: + ./a.out + @echo + ./a.out -h + @echo + ./a.out -f tests/calendar.ics diff --git a/src/cli_arg_parsing.c b/src/cli_arg_parsing.c new file mode 100644 index 0000000..167ca6e --- /dev/null +++ b/src/cli_arg_parsing.c @@ -0,0 +1,41 @@ +#include "cli_arg_parsing.h" +#include +#include +#include +#include + +void usage() { + printf ("-h\tprint this help\n"); + printf ("-f\tspecify ics file path\n"); + exit(0); +} + +void get_cli_args(int argc, char **argv, char **file_name) { + int opt = 0; + + memset(file_name, '\0', strlen(*file_name)); + + if (argc < 2) { + char *home = getenv("HOME"); + *file_name = home; + + if (home != NULL) { + strcat(*file_name, "/.local/share/evolution/calendar/system/calendar.ics"); + } else { + printf ("Environment variable HOME is not set.\n"); + exit(1); + } + return; + } + + while ((opt = getopt(argc, argv, "f:h")) != -1) { + switch(opt) { + case 'f': + *file_name = optarg; + break; + case 'h': + usage(); + } + } +} + diff --git a/src/cli_arg_parsing.h b/src/cli_arg_parsing.h new file mode 100644 index 0000000..eb496de --- /dev/null +++ b/src/cli_arg_parsing.h @@ -0,0 +1,5 @@ +#pragma once + +void usage(); + +void get_cli_args(int argc, char **argv, char **file_name); diff --git a/src/main.c b/src/main.c index 29a9a10..758905f 100644 --- a/src/main.c +++ b/src/main.c @@ -1,3 +1,4 @@ +#include "cli_arg_parsing.h" #include "date_time_handling.h" #include "list_handling.h" #include "cut_string.h" @@ -12,21 +13,13 @@ #include #include -int main() { - //const char ICS_PATH[] = "tests/calendar.ics"; - char *ICS_PATH; - char *HOME = getenv("HOME"); - - if (HOME != NULL) { - ICS_PATH = strcat(HOME, "/.local/share/evolution/calendar/system/calendar.ics"); - } else { - printf ("Environment variable HOME is not set.\n"); - return 1; - } +int main(int argc, char **argv) { + char *ics_path = ""; + get_cli_args(argc, argv, &ics_path); char my_line[4096] = ""; - int myfd = open(ICS_PATH, O_RDONLY); + int myfd = open(ics_path, O_RDONLY); if (myfd == -1) { perror ("Error opening file"); return 1;