Advertisement
rockdrilla

read all file contents

Nov 15th, 2018
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void * fread_all(const char * filename) {
  6.         FILE            * f = NULL;
  7.         char            * buf = NULL, * buf_t = NULL;
  8.         const size_t    m_shift = 14, m_thres = 1 << m_shift;
  9.         size_t          buf_len = 0, read = 0, i = 0;
  10.  
  11.         f = fopen(filename, "r");
  12.         if (!f) { return NULL; }
  13.  
  14.         buf = malloc(m_thres);
  15.         if (!buf) { goto file_cleanup; }
  16.  
  17.         memset(buf, 0, m_thres);
  18.  
  19.         while (1) {
  20.                 buf_t = buf + buf_len;
  21.                 read = fread(buf_t, 1, m_thres, f);
  22.                 if (!read) { break; }
  23.  
  24.                 buf_len += read;
  25.                 if (read != m_thres) { break; }
  26.  
  27.                 buf_t = realloc(buf, ((buf_len >> m_shift) + 1) << m_shift);
  28.                 if (!buf_t) { goto buf_cleanup; }
  29.  
  30.                 buf = buf_t;
  31.                 memset(buf + buf_len, 0, m_thres);
  32.         }
  33.  
  34.         if (!buf_len) { goto buf_cleanup; }
  35.         if (!buf) { goto file_cleanup; }
  36.  
  37.         // trim trailing \n's
  38.         for (i = buf_len - 1; i; i--) {
  39.                 if (buf[i] == '\0') { continue; }
  40.                 if (buf[i] == '\n') {
  41.                         buf[i] = '\0';
  42.                         continue;
  43.                 }
  44.                 break;
  45.         }
  46.  
  47.         goto ok;
  48.  
  49. buf_cleanup:
  50.         if (buf) { free(buf); buf = NULL; }
  51.  
  52. ok:
  53. file_cleanup:
  54.         if (f) { fclose(f); f = NULL; }
  55.  
  56.         return buf;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement