aboutsummaryrefslogtreecommitdiff
path: root/filesystem/src/filesystem.c
blob: b228e85bb1b2ec14c0885724d23fbee4f0071bf1 (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
#include <filesystem.h>

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

size_t get_file_size(FILE* file) {
  assert(file);
  const long int starting_pos = ftell(file);
  if (starting_pos == -1) {
    return (size_t)-1;
  }
  if (fseek(file, 0, SEEK_END) != 0) {
    return (size_t)-1;
  }
  const size_t file_size = ftell(file);
  if (file_size == (size_t)-1) {
    return (size_t)-1;
  }
  if (fseek(file, starting_pos, SEEK_SET) != 0) {
    return (size_t)-1;
  }
  return file_size;
}

void* read_file(const char* filepath) {
  assert(filepath);

  void* data = 0;

  FILE* file = fopen(filepath, "rb");
  if (!file) {
    return 0;
  }
  const size_t file_size = get_file_size(file);
  if (file_size == (size_t)-1) {
    goto cleanup;
  }

  data = calloc(1, file_size);
  if (!data) {
    goto cleanup;
  }
  if (fread(data, 1, file_size, file) != file_size) {
    goto cleanup;
  }

  return data;

cleanup:
  fclose(file);
  if (data) {
    free(data);
  }
  return 0;
}