summaryrefslogtreecommitdiff
path: root/src/platform/file.c
blob: 44aa9d04e3835b02c6fb045e5e6ae7570ad43d01 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "file.h"

#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

#include "log.h"
#include "mem.h"
#include "str.h"

const char *string_from_file(const char *path) {
  FILE *f = fopen(path, "rb");
  if (f == NULL) {
    ERROR("Error reading file: %s. errno: %d", path, errno);
    return NULL;
  }
  if (ferror(f)) {
    ERROR("Error reading file: %s. errno: %d", path, errno);
    return NULL;
  }
  fseek(f, 0, SEEK_END);
  long fsize = ftell(f);
  rewind(f);

  char *string = malloc(fsize + 1);
  fread(string, fsize, 1, f);
  fclose(f);

  string[fsize] = '\0';

  return string;
}

str8_opt str8_from_file(arena *a, str8 path) {
  char *p = cstr(a, path);
  str8_opt result = { .has_value = false };

  FILE *f = fopen(p, "rb");
  if (f == NULL) {
    ERROR("Error reading file: %s. errno: %d", path, errno);
    return result;
  }
  if (ferror(f)) {
    ERROR("Error reading file: %s. errno: %d", path, errno);
    return result;
  }
  fseek(f, 0, SEEK_END);
  long fsize = ftell(f);
  rewind(f);

  u8 *raw = arena_alloc(a, fsize + 1);
  str8 contents = str8_create(raw, fsize);
  contents.buf[contents.len] = '\0';

  fread(raw, fsize, 1, f);
  fclose(f);
  result.contents = contents;
  result.has_value = true;

  return result;
}