/* Read from fp until EOF and return a string of everything read. */ static char * load_text_fp (void *ctx, FILE *fp) { #define CHUNK 4096 char *text = NULL; size_t text_size = 0; size_t total_read = 0; size_t bytes; while (1) { if (total_read + CHUNK + 1 > text_size) { text_size = text_size ? text_size * 2 : CHUNK + 1; text = reralloc_size (ctx, text, text_size); if (text == NULL) { fprintf (stderr, "Out of memory\n"); return NULL; } } bytes = fread (text + total_read, 1, CHUNK, fp); total_read += bytes; if (bytes < CHUNK) { break; } } text[total_read] = '\0'; return text; }
/* Read from fd until EOF and return a string of everything read. */ static char * load_text_fd (void *ctx, int fd) { #define CHUNK 4096 char *text = NULL; ssize_t text_size = 0; ssize_t total_read = 0; ssize_t bytes; while (1) { if (total_read + CHUNK + 1 > text_size) { text_size = text_size ? text_size * 2 : CHUNK + 1; text = reralloc_size (ctx, text, text_size); if (text == NULL) { fprintf (stderr, "Out of memory\n"); return NULL; } } bytes = read (fd, text + total_read, CHUNK); if (bytes < 0) { fprintf (stderr, "Error while reading: %s\n", strerror (errno)); ralloc_free (text); return NULL; } if (bytes == 0) { break; } total_read += bytes; } text[total_read] = '\0'; return text; }