From: Fletcher T. Penney Date: Fri, 6 May 2016 15:38:34 +0000 (-0400) Subject: CHANGED: Use faster method of getting input from stdin or a file -- old method was... X-Git-Tag: 0.1.0a~8^2~2 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=5c1561cd5806d099ddb6693b41ecbb5df539f840;p=multimarkdown CHANGED: Use faster method of getting input from stdin or a file -- old method was *slow* --- diff --git a/src/main.c b/src/main.c index 22d0ff2..8e88642 100644 --- a/src/main.c +++ b/src/main.c @@ -26,24 +26,48 @@ #include "GLibFacade.h" -char * stdin_buffer() { - /* Read from stdin and return a char * - `result` will need to be freed elsewhere */ +#define kBUFFERSIZE 4096 // How many bytes to read at a time + +GString * stdin_buffer() { + /* Read from stdin and return a GString * + `buffer` will need to be freed elsewhere */ + + char chunk[kBUFFERSIZE]; + size_t bytes; GString * buffer = g_string_new(""); - char curchar; - char * result; - while ((curchar = fgetc(stdin)) != EOF) - g_string_append_c(buffer, curchar); + while ((bytes = fread(chunk, 1, kBUFFERSIZE, stdin)) > 0) { + g_string_append_c_array(buffer, chunk, bytes); + } fclose(stdin); - result = buffer->str; + return buffer; +} + +GString * scan_file(char * fname) { + /* Read from stdin and return a GString * + `buffer` will need to be freed elsewhere */ + + char chunk[kBUFFERSIZE]; + size_t bytes; + + FILE * file; + + if ((file = fopen(fname, "r")) == NULL ) { + return NULL; + } + + GString * buffer = g_string_new(""); + + while ((bytes = fread(chunk, 1, kBUFFERSIZE, file)) > 0) { + g_string_append_c_array(buffer, chunk, bytes); + } - g_string_free(buffer, false); + fclose(file); - return result; + return buffer; } int main( int argc, char** argv ) {