aboutsummaryrefslogtreecommitdiff
path: root/filesystem/src/filesystem.c
blob: f6bb693b2806cd3900f2f1409564c09ac754be3c (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <filesystem.h>

#include <assert.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;
}

bool make_relative_path(
    const char* filepath, const char* path, char* relative,
    size_t relative_length) {
  assert(filepath);
  assert(path);
  assert(relative);

  const size_t filepath_len = strlen(filepath);
  const size_t path_len     = strlen(path);
  assert(filepath_len < relative_length);
  assert(path_len < relative_length);

  // Handle empty filepath.
  if (filepath_len == 0) {
    memcpy(relative, path, path_len);
    return true;
  }

  // Search for the last / in the file path to get its parent directory.
  assert(filepath_len > 0);
  size_t tm_dir_len = 0;
  for (tm_dir_len = strlen(filepath) - 1; tm_dir_len > 0; --tm_dir_len) {
    if (filepath[tm_dir_len] == '/') {
      break;
    }
  }
  tm_dir_len++; // Preserve the backslash.

  // Copy the file path where the parent dir ends.
  // Make sure there is enough space in the output.
  if ((tm_dir_len + path_len + 1) >= relative_length) {
    return false;
  }
  memcpy(relative, filepath, tm_dir_len);
  memcpy(&relative[tm_dir_len], path, path_len);

  return true;
}