1

Pretty printing

This commit is contained in:
Alex Yatskov 2016-11-02 20:37:11 -07:00
parent fafda50e96
commit 0c0952840e
3 changed files with 30 additions and 12 deletions

34
main.c
View File

@ -18,6 +18,8 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <getopt.h>
#include <stdbool.h>
#include "convert.h" #include "convert.h"
#include "util.h" #include "util.h"
@ -160,15 +162,29 @@ static void export_book(const char path[], Book* book) {
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
if (argc != 2) { bool pretty_print = false;
fprintf(stderr, "usage: %s dictionary_path\n", argv[0]);
return 2; 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 = {}; if (optind >= argc) {
export_book(argv[1], &book); fprintf(stderr, "Usage: %s [-p] dictionary_path\n", argv[0]);
dump_book(&book, stdout); exit(EXIT_FAILURE);
free_book(&book);
return 1;
} }
Book book = {};
export_book(argv[optind], &book);
dump_book(&book, pretty_print, stdout);
free_book(&book);
return 0;
} }

4
util.c
View File

@ -136,11 +136,11 @@ static void encode_book(Book* book, json_t* book_json) {
json_decref(subbook_json_array); 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(); json_t* book_json = json_object();
encode_book(book, book_json); 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) { if (output != NULL) {
fputs(output, fp); fputs(output, fp);
} }

4
util.h
View File

@ -20,7 +20,9 @@
#define UTIL_H #define UTIL_H
#include <stdlib.h> #include <stdlib.h>
#include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include "eb/eb/eb.h" #include "eb/eb/eb.h"
/* /*
@ -72,7 +74,7 @@ typedef enum {
char* read_book_data(EB_Book* book, const EB_Position* position, ReadMode mode); char* read_book_data(EB_Book* book, const EB_Position* position, ReadMode mode);
void free_book(Book* book); void free_book(Book* book);
void dump_book(Book* book, FILE* fp); void dump_book(Book* book, bool pretty_print, FILE* fp);
#endif #endif