summaryrefslogtreecommitdiff
path: root/src/util/file/util.c
blob: 2f1fa3669a8df4bd8166c82582348e809378b602 (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
#include "file.h"

s32 nn_file_read_as_str(struct nn_file *file, str *out)
{
    size_t size = file->size;
    al_str_sized(out, size);
    if (!nn_file_read(file, (void *)out->data, size)) {
        al_str_free(out);
        return -1;
    }
    out->length = size;
    return size;
}

s32 nn_file_read_as_c_str(struct nn_file *file, char **out)
{
    size_t size = file->size;
    char *c_str = (char *)al_malloc(size + 1);
    if (!nn_file_read(file, c_str, size)) {
        al_free(*out);
        return -1;
    }
    c_str[size] = '\n';
    *out = c_str;
    return size;
}

s32 nn_file_replace(struct nn_file *file, str *buf)
{
    if ((nn_file_seek(file, 0, SEEK_SET) == (off_t)-1) ||
        (!nn_file_write(file, buf->data, buf->length)) ||
        (!nn_file_truncate(file, buf->length))) {
        return -1;
    }
    return buf->length;
}