From 72127b505937410f9b00d3c649a85bde18593bfb Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 30 Apr 2019 01:56:13 -0300 Subject: [PATCH] add argument consumption for better journal messages --- src/journal/emotion.c | 5 ++-- src/journal/main.c | 61 ++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/src/journal/emotion.c b/src/journal/emotion.c index a316ec7..143c84b 100644 --- a/src/journal/emotion.c +++ b/src/journal/emotion.c @@ -4,7 +4,8 @@ void handle_emotion(FILE *journal, char* msg) { - // TODO: add newline to msg - journal_write(journal, msg); + char formatted[512]; + sprintf(formatted, "%s\n", msg); + journal_write(journal, formatted); return; } diff --git a/src/journal/main.c b/src/journal/main.c index 6c243e1..640dcfa 100644 --- a/src/journal/main.c +++ b/src/journal/main.c @@ -1,11 +1,51 @@ #include #include +#include #include "emotion.h" #include "journal.h" #define TOPICS 10 +// go through all elements of argv[2] and beyond +// and join them together in a string +char *extract_handler_msg(int argc, char **argv) +{ + int cur = 0; + + // allocate an empty slot to start with. + char *res = malloc(cur); + + // iterate through each argument + for(int i = 2; argv[i] != NULL; i++) + { + // catch it, get its length + char *word = argv[i]; + int wordlen = strlen(word); + + // increase the size of our current things by + // arg length + 1 (for a whitespace) + cur += wordlen; + res = realloc(res, cur + 1); + + // only prepend our whitespace if we AREN'T + // at the first argument. + if(i != 2) + { + res[cur - wordlen] = ' '; + cur++; + } + + // merge our current results with the current arg + for(int j = 0; j < wordlen; j++) + { + res[cur - wordlen + j] = word[j]; + } + } + + return res; +} + int main(int argc, char** argv) { if(argc < 2) @@ -15,7 +55,6 @@ int main(int argc, char** argv) } char *topic = argv[1]; - printf("load topic %s\n", topic); const char* topics[TOPICS] = { "emotion" @@ -25,7 +64,16 @@ int main(int argc, char** argv) handle_emotion, }; - for(int i = 0; i < TOPICS; i++) + if(strcmp(topic, "list") == 0) + { + // list all topics + for(int i = 0; topics[i] != NULL; i++) + printf("%s ", topics[i]); + printf("\n"); + return 0; + } + + for(int i = 0; topics[i] != NULL; i++) { const char* cur_topic = topics[i]; @@ -34,9 +82,16 @@ int main(int argc, char** argv) void (*fun_ptr)(FILE*, char*) = handlers[i]; FILE* journal_file = journal_open(topic); - fun_ptr(journal_file, "hello world"); + + char *handler_message = extract_handler_msg(argc, argv); + printf("'%s'\n", handler_message); + + // the joined args[2] and beyond come as the + // second argument + fun_ptr(journal_file, handler_message); journal_close(journal_file); + free(handler_message); printf("done\n"); return 0; }