about summary refs log tree commit diff
path: root/src/readfile.c
blob: fb756de30352a5291506950cd0f61d3f5b663cd6 (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
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "utils.h"


char *readfile(const char *name)
{
    char *code, chr;
    FILE *file = fopen(name, "r");
    if (errno) die(1, strerror(errno));
        fseek(file, 0, SEEK_END);
        size_t size = ftell(file);
        fseek(file, 0, SEEK_SET);
        code = calloc(size + 1, sizeof(*code));

        for (int i = 0; i < size; ++i)
        {
            if ((chr = fgetc(file)) == EOF)
            {
                if (errno)
                    die(1, strerror(errno));
                else
                    break;
            }
            code[i] = chr;
        }
    fclose(file);

    return code;
}