|
2 | 2 |
|
3 | 3 | main.c -- Template main() |
4 | 4 |
|
5 | | - Copyright © 2015 Fletcher T. Penney. |
| 5 | + Copyright © 2015-2016 Fletcher T. Penney. |
6 | 6 |
|
7 | 7 |
|
8 | 8 | This program is free software you can redistribute it and/or modify |
|
26 | 26 |
|
27 | 27 | #include "GLibFacade.h" |
28 | 28 |
|
29 | | -char * stdin_buffer() { |
30 | | - /* Read from stdin and return a char * |
31 | | - `result` will need to be freed elsewhere */ |
| 29 | +#define kBUFFERSIZE 4096 // How many bytes to read at a time |
| 30 | + |
| 31 | +GString * stdin_buffer() { |
| 32 | + /* Read from stdin and return a GString * |
| 33 | + `buffer` will need to be freed elsewhere */ |
| 34 | + |
| 35 | + char chunk[kBUFFERSIZE]; |
| 36 | + size_t bytes; |
32 | 37 |
|
33 | 38 | GString * buffer = g_string_new(""); |
34 | | - char curchar; |
35 | | - char * result; |
36 | 39 |
|
37 | | - while ((curchar = fgetc(stdin)) != EOF) |
38 | | - g_string_append_c(buffer, curchar); |
| 40 | + while ((bytes = fread(chunk, 1, kBUFFERSIZE, stdin)) > 0) { |
| 41 | + g_string_append_c_array(buffer, chunk, bytes); |
| 42 | + } |
39 | 43 |
|
40 | 44 | fclose(stdin); |
41 | 45 |
|
42 | | - result = buffer->str; |
| 46 | + return buffer; |
| 47 | +} |
| 48 | + |
| 49 | +GString * scan_file(char * fname) { |
| 50 | + /* Read from stdin and return a GString * |
| 51 | + `buffer` will need to be freed elsewhere */ |
| 52 | + |
| 53 | + char chunk[kBUFFERSIZE]; |
| 54 | + size_t bytes; |
| 55 | + |
| 56 | + FILE * file; |
| 57 | + |
| 58 | + if ((file = fopen(fname, "r")) == NULL ) { |
| 59 | + return NULL; |
| 60 | + } |
| 61 | + |
| 62 | + GString * buffer = g_string_new(""); |
| 63 | + |
| 64 | + while ((bytes = fread(chunk, 1, kBUFFERSIZE, file)) > 0) { |
| 65 | + g_string_append_c_array(buffer, chunk, bytes); |
| 66 | + } |
43 | 67 |
|
44 | | - g_string_free(buffer, false); |
| 68 | + fclose(file); |
45 | 69 |
|
46 | | - return result; |
| 70 | + return buffer; |
47 | 71 | } |
48 | 72 |
|
49 | 73 | int main( int argc, char** argv ) { |
|
0 commit comments