From 0c0952840e9339dbfa52d67a269596f35c213ea1 Mon Sep 17 00:00:00 2001 From: Alex Yatskov Date: Wed, 2 Nov 2016 20:37:11 -0700 Subject: [PATCH] Pretty printing --- main.c | 34 +++++++++++++++++++++++++--------- util.c | 4 ++-- util.h | 4 +++- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/main.c b/main.c index 17b022c..25ad8d6 100644 --- a/main.c +++ b/main.c @@ -18,6 +18,8 @@ #include #include +#include +#include #include "convert.h" #include "util.h" @@ -160,15 +162,29 @@ static void export_book(const char path[], Book* book) { } int main(int argc, char *argv[]) { - if (argc != 2) { - fprintf(stderr, "usage: %s dictionary_path\n", argv[0]); - return 2; + bool pretty_print = false; + + char opt; + while ((opt = getopt(argc, argv, "p")) != -1) { + switch (opt) { + case 'p': + pretty_print = true; + break; + default: + exit(EXIT_FAILURE); + break; + } } - else { - Book book = {}; - export_book(argv[1], &book); - dump_book(&book, stdout); - free_book(&book); - return 1; + + if (optind >= argc) { + fprintf(stderr, "Usage: %s [-p] dictionary_path\n", argv[0]); + exit(EXIT_FAILURE); } + + Book book = {}; + export_book(argv[optind], &book); + dump_book(&book, pretty_print, stdout); + free_book(&book); + + return 0; } diff --git a/util.c b/util.c index f9b17fc..a57c429 100644 --- a/util.c +++ b/util.c @@ -136,11 +136,11 @@ static void encode_book(Book* book, json_t* book_json) { json_decref(subbook_json_array); } -void dump_book(Book* book, FILE* fp) { +void dump_book(Book* book, bool pretty_print, FILE* fp) { json_t* book_json = json_object(); encode_book(book, book_json); - char* output = json_dumps(book_json, JSON_COMPACT); + char* output = json_dumps(book_json, pretty_print ? JSON_INDENT(4) : JSON_COMPACT); if (output != NULL) { fputs(output, fp); } diff --git a/util.h b/util.h index 3d706e6..83f7f07 100644 --- a/util.h +++ b/util.h @@ -20,7 +20,9 @@ #define UTIL_H #include +#include #include + #include "eb/eb/eb.h" /* @@ -72,7 +74,7 @@ typedef enum { char* read_book_data(EB_Book* book, const EB_Position* position, ReadMode mode); void free_book(Book* book); -void dump_book(Book* book, FILE* fp); +void dump_book(Book* book, bool pretty_print, FILE* fp); #endif