From 8d3a5e5f51153c38f4c5b20a309af2b6e5bf686d Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Sun, 20 Dec 2020 23:57:31 -0500 Subject: [PATCH] file reading --- parser.c | 52 +++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/parser.c b/parser.c index 9a2c7f9..3c28349 100644 --- a/parser.c +++ b/parser.c @@ -10,6 +10,8 @@ typedef struct TodoItem { char** items; } TodoItem; +char* read_file(char* file_name, long* size); + /* callbacks to parser */ int enter_block(MD_BLOCKTYPE type, void* detail, void* userdata); int leave_block(MD_BLOCKTYPE type, void* detail, void* userdata); @@ -19,7 +21,7 @@ int text(MD_TEXTTYPE type, const MD_CHAR* text, MD_SIZE size, void* userdata); void debug_log(const char* msg, void* userdata); void syntax(void); -static MD_PARSER parser = { +const MD_PARSER parser = { 0, MD_DIALECT_COMMONMARK, &enter_block, @@ -31,22 +33,54 @@ static MD_PARSER parser = { &syntax }; -static char task_md[] = "###"; int main(int argc, char** argv) { - FILE* input_file; - int todo_length; + char* input_buffer; + long input_size; - input_file = fopen("test_board.md", "r"); - if (!input_file) { - printf("Something went wrong opening file"); - return 1; - } + input_buffer = read_file("test_board.md", &input_size); + + md_parse(input_buffer, input_size, &parser, NULL); return 0; } +char* +read_file(char* file_name, long* size) +{ // apparently using seek isnt the greatest, may change to chunk reading later + FILE* file; + char* output; + long fsize; + + file = fopen(file_name, "r"); + if (file == NULL) { + printf("Something went wrong opening file\n"); + return NULL; + } + + fseek(file, 0, SEEK_END); + fsize = ftell(file); + fseek(file, 0, SEEK_SET); + + output = malloc(fsize+1); // maybe error check malloc + fread(output, 1, fsize, file); + if (ferror(file)) { + printf("Something went wrong reading file\n"); + fclose(file); + free(output); + return NULL; + } + output[fsize] = 0; // add null terminator + + /* clean up */ + fclose(file); + + /* return */ + *size = fsize; + return output; +} + int enter_block(MD_BLOCKTYPE type, void* detail, void* userdata) { -- 2.20.1