From 7da497992bb69f356ef25929137a3ba13c9a75ae Mon Sep 17 00:00:00 2001 From: Tristan Riehs Date: Sat, 1 Jun 2024 02:18:07 +0900 Subject: Add basic command-line arguments parsing --- src/calculer.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/src/calculer.c b/src/calculer.c index 062fff6..5eefb87 100644 --- a/src/calculer.c +++ b/src/calculer.c @@ -23,6 +23,7 @@ #include #include #include +#include #include "linenoise.h" @@ -69,8 +70,35 @@ measure_after(void *data, int correct) return bytes_written != fwrite(logbuf, 1, bytes_written, logfile); } +#define print_opt_noarg(opt, desc) \ + fprintf(stream, " -"opt"\t"desc"\n") + + +void +print_usage(FILE *stream) +{ + fprintf(stream, "Usage: calculer [OPTIONS]\n"); + fprintf(stream, "OPTIONS\n"); + print_opt_noarg("V", "Print version and exit."); + print_opt_noarg("h", "Print help and exit."); +} + +void +print_help(void) +{ + printf("calculer -- train mental calculus\n"); + printf("calculer is licensed under the GPL3 License.\n"); + print_usage(stdout); +} + +void +print_version(void) +{ + printf("%s\n", VERSION); +} + int -main(void) +main(int argc, char *argv[]) { srand(time(NULL)); logfile = fopen("./calculer.log", "a"); @@ -81,6 +109,29 @@ main(void) size_t bytes_written = strftime(logbuf, sizeof(logbuf), "%F\t", tm); assert(bytes_written); + int opt; + while ((opt = getopt(argc, argv, ":Vh")) != -1) + { + switch (opt) + { + case 'V': + print_version(); + exit(0); + case 'h': + print_help(); + exit(0); + case ':': + fprintf(stderr, + "calculer: option %d requires an argument\n", + optopt); + print_usage(stderr); + exit(1); + default: + print_usage(stderr); + exit(1); + } + } + while (1) { char prompt[32] = {0}; -- cgit v1.2.3