aboutsummaryrefslogtreecommitdiff
path: root/fileutils.c
blob: 137373bff4ed3e84740cfba977c6983854ea6eb8 (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
40
41
42
43
44
45
46
47
#include "fileutils.h"
#include "alloc.h"

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pwd.h>
#include <unistd.h>

const char* get_home_dir() {
    const char *home_dir = getenv("HOME");
    if(!home_dir) {
        struct passwd *pw = getpwuid(getuid());
        home_dir = pw->pw_dir;
    }
    return home_dir;
}

int file_get_content(const char *filepath, char **data, long *size) {
    int result = 0;
    FILE *file = fopen(filepath, "rb");
    if(!file) {
        int err = -errno;
        perror(filepath);
        return err;
    }

    fseek(file, 0, SEEK_END);
    *size = ftell(file);
    if(*size == -1) {
        fprintf(stderr, "Failed to tell the size of file %s, is it not a file?\n", filepath);
        result = -1;
        goto cleanup;
    }
    fseek(file, 0, SEEK_SET);

    *data = alloc_or_crash(*size);
    if((long)fread(*data, 1, *size, file) != *size) {
        fprintf(stderr, "Failed to read all bytes in file %s\n", filepath);
        result = -1;
        goto cleanup;
    }

    cleanup:
    fclose(file);
    return result;
}