A reimplementation of Mario Kart Wii's physics engine in C++
Loading...
Searching...
No Matches
File.cc
1#include "File.hh"
2
3#include <egg/core/Heap.hh>
4
5#include <cstdio>
6#include <cstdlib>
7#include <cstring>
8#include <fstream>
9
10namespace Kinoko::Abstract::File {
11
12u8 *Load(const char *path, size_t &size) {
13 char filepath[256];
14
15 if (path[0] == '/') {
16 path++;
17 }
18
19 const char *root = std::getenv("KINOKO_FILESYSTEM_ROOT");
20
21 if (root && root[0] != '\0') {
22 // path relative to KINOKO_FILESYSTEM_ROOT
23#ifdef _WIN32
24 const char separator = '\\';
25#else
26 const char separator = '/';
27#endif
28
29 size_t rootLen = std::strlen(root);
30 bool rootEndsWithSep = root[rootLen - 1] == separator;
31
32 if (rootEndsWithSep) {
33 std::snprintf(filepath, sizeof(filepath), "%s%s", root, path);
34 } else {
35 std::snprintf(filepath, sizeof(filepath), "%s%c%s", root, separator, path);
36 }
37 } else {
38 // Path relative to current working directory
39 std::snprintf(filepath, sizeof(filepath), "%s", path);
40 }
41
42 std::ifstream file(filepath, std::ios::binary);
43 if (!file) {
44 PANIC("Failed to load file %s! (KINOKO_FILESYSTEM_ROOT=%s)", path, root ? root : "(unset)");
45 }
46
47 file.seekg(0, std::ios::end);
48 size = file.tellg();
49 file.seekg(0, std::ios::beg);
50
51 u8 *buffer = static_cast<u8 *>(EGG::egg_alloc(size, 4));
52 file.read(reinterpret_cast<char *>(buffer), size);
53
54 return buffer;
55}
56
57u8 *LoadHost(const char *path, size_t &size) {
58 char filepath[256];
59
60 std::snprintf(filepath, sizeof(filepath), "%s", path);
61
62 std::ifstream file(filepath, std::ios::binary);
63 if (!file) {
64 PANIC("Failed to load file %s!", path);
65 }
66
67 file.seekg(0, std::ios::end);
68 size = file.tellg();
69 file.seekg(0, std::ios::beg);
70
71 u8 *buffer = new u8[size];
72 file.read(reinterpret_cast<char *>(buffer), size);
73
74 return buffer;
75}
76
77void Append(const char *path, const char *data, size_t size) {
78 std::ofstream stream;
79 stream.open(path, std::ios::app | std::ios::binary);
80 stream.write(data, size);
81}
82
83int Remove(const char *path) {
84 return std::remove(path);
85}
86
87} // namespace Kinoko::Abstract::File