aboutsummaryrefslogtreecommitdiff
path: root/src/utils/file.c
blob: cdb2dfe564030a4d99671aa0f1a670322aff2d95 (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
#include "file.h"

#include <stdio.h>
#include <string.h>
#include <utils/memory/memory.h>

Code *read_whole_file(const char *path) {
  FILE *file = fopen(path, "r");
  if (!file) {
    fprintf(stderr, "could not open file at path '%s'\n", path);
    return NULL;
  }
  fseek(file, 0, SEEK_END);
  const size_t file_size = ftell(file);
  fseek(file, 0, SEEK_SET);

  char *str = a404m_malloc((file_size + 1) * sizeof(char));

  fread(str, file_size, 1, file);
  str[file_size] = '\0';

  fclose(file);
  Code *code = a404m_malloc(sizeof(*code));

  size_t pathLen = strlen(path);
  code->code = str;
  code->filePath = a404m_malloc(pathLen+1);

  memcpy(code->filePath, path, pathLen+1);

  return code;
}