summaryrefslogtreecommitdiff
path: root/src/util/file.c
blob: 38eb9badfa3b2d1108be5511cc5165d4b7ba5d38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <string.h>
#include "file.h"

FILE *file_open(str s_path, const char *mode)
{
    NULTERM(s_path, path)
    return fopen(path, mode);
}

static bool file_size(FILE *file, size_t *size)
{
    if (fseek(file, 0, SEEK_END) == -1)
        return false;
    long end = ftell(file);
    fseek(file, 0, SEEK_SET);
    if (end == -1)
        return false;
    *size = end;
    return true;
}

str file_read(FILE *file)
{
    size_t size;
    if (file_size(file, &size)) {
        str s;
        array_alloc(&s, size);
        s.len = fread(s.ptr, 1, size, file);
        return s;
    } else {
        strbuf buf = {};
        size_t n_read;
        do {
            arraybuf_grow(&buf, BUFSIZ);
            buf.len += (n_read = fread(buf.ptr+buf.len, 1, BUFSIZ, file));
        } while (n_read == BUFSIZ);
        return (str) arraybuf_cast(buf);
    }
}