damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

readfile.h (1078B)


      1 #ifndef READFILE_H
      2 #define READFILE_H
      3 
      4 #ifdef __cplusplus
      5 extern "C" {
      6 #endif
      7 
      8 #include <stdio.h>
      9 #include <stdlib.h>
     10 
     11 static char *readfile(const char *filename, size_t max_size, size_t *size_out)
     12 {
     13     FILE *fp;
     14     long k;
     15     size_t size, pos, n, _out;
     16     char *buf;
     17 
     18     size_out = size_out ? size_out : &_out;
     19 
     20     fp = fopen(filename, "rb");
     21     size = 0;
     22     buf = 0;
     23 
     24     if (!fp) {
     25         goto fail;
     26     }
     27     fseek(fp, 0L, SEEK_END);
     28     k = ftell(fp);
     29     if (k < 0) goto fail;
     30     size = (size_t)k;
     31     *size_out = size;
     32     if (max_size > 0 && size > max_size) {
     33         goto fail;
     34     }
     35     rewind(fp);
     36     buf = (char *)malloc(size ? size : 1);
     37     if (!buf) {
     38         goto fail;
     39     }
     40     pos = 0;
     41     while ((n = fread(buf + pos, 1, size - pos, fp))) {
     42         pos += n;
     43     }
     44     if (pos != size) {
     45         goto fail;
     46     }
     47     fclose(fp);
     48     *size_out = size;
     49     return buf;
     50 
     51 fail:
     52     if (fp) {
     53         fclose(fp);
     54     }
     55     if (buf) {
     56         free(buf);
     57     }
     58     *size_out = size;
     59     return 0;
     60 }
     61 
     62 #ifdef __cplusplus
     63 }
     64 #endif
     65 
     66 #endif /* READFILE_H */