Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void * fread_all(const char * filename) {
- FILE * f = NULL;
- char * buf = NULL, * buf_t = NULL;
- const size_t m_shift = 14, m_thres = 1 << m_shift;
- size_t buf_len = 0, read = 0, i = 0;
- f = fopen(filename, "r");
- if (!f) { return NULL; }
- buf = malloc(m_thres);
- if (!buf) { goto file_cleanup; }
- memset(buf, 0, m_thres);
- while (1) {
- buf_t = buf + buf_len;
- read = fread(buf_t, 1, m_thres, f);
- if (!read) { break; }
- buf_len += read;
- if (read != m_thres) { break; }
- buf_t = realloc(buf, ((buf_len >> m_shift) + 1) << m_shift);
- if (!buf_t) { goto buf_cleanup; }
- buf = buf_t;
- memset(buf + buf_len, 0, m_thres);
- }
- if (!buf_len) { goto buf_cleanup; }
- if (!buf) { goto file_cleanup; }
- // trim trailing \n's
- for (i = buf_len - 1; i; i--) {
- if (buf[i] == '\0') { continue; }
- if (buf[i] == '\n') {
- buf[i] = '\0';
- continue;
- }
- break;
- }
- goto ok;
- buf_cleanup:
- if (buf) { free(buf); buf = NULL; }
- ok:
- file_cleanup:
- if (f) { fclose(f); f = NULL; }
- return buf;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement