files.c (985B)
1 /* See LICENSE file for copyright and license details. */ 2 3 #include "files.h" 4 5 6 char* freadall(FILE* input, size_t* length) { 7 char *buf = malloc(BUF_SIZE); 8 size_t used = 0; 9 size_t len = 0; 10 11 do { 12 buf = realloc(buf, BUF_SIZE + used); 13 len = fread(buf + used, sizeof(char), BUF_SIZE, input); 14 used = used + len; 15 } while (len != 0); 16 17 buf = realloc(buf, used + 1); 18 buf[used] = '\0'; 19 20 *length = used; 21 22 return buf; 23 } 24 25 char* freadline(FILE *input) { 26 char *buf = malloc(BUF_SIZE); 27 size_t used = 0; 28 29 while(1) { 30 buf = realloc(buf, BUF_SIZE + used); 31 if (fgets(buf + used, BUF_SIZE, input) == NULL) { 32 break; 33 } 34 char *new_line = strchr(buf + used, '\n'); 35 if (new_line != NULL) { 36 used = new_line - buf; 37 break; 38 } else { 39 used += BUF_SIZE - 1; 40 } 41 } 42 43 buf = realloc(buf, used + 1); 44 buf[used] = '\0'; 45 46 return buf; 47 } 48