-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.hpp
73 lines (59 loc) · 2.41 KB
/
files.hpp
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
#include "memory.hpp"
#if !defined(ACHILLES_FILES_HPP)
#define ACHILLES_FILES_HPP
// this file requires <stdio.h> for 'fopen' and friends
#include <cstdio>
#include "types.hpp"
#include "assert.hpp"
namespace achilles {
namespace files {
using namespace memory;
enum FileMode : u8 {
FILE_BINARY,
FILE_TEXT,
};
inline Block readFile(const char *path, Allocator &allocator = GlobalAllocator::instance(), FileMode mode = FILE_BINARY) {
FILE* file = nullptr;
constexpr u64 READ_BUFFER_SIZE = 256;
const char *readMode = "rb";
if (mode == FILE_TEXT) readMode = "r";
if ((file = std::fopen(path, readMode)) != nullptr) {
std::fseek(file, 0, SEEK_END);
u64 fileSize = ftell(file);
std::rewind(file);
u8 *memory = allocator.allocate(fileSize);
u64 totalBytesRead = 0;
u8 buffer[READ_BUFFER_SIZE];
while (!std::feof(file)) {
u64 readBytes = std::fread(buffer, sizeof *buffer, READ_BUFFER_SIZE, file);
if (readBytes == 0) break;
for (u64 i = 0; i < readBytes; i++) {
memory[totalBytesRead++] = buffer[i];
}
}
std::fclose(file);
return Block {memory, fileSize, allocator};
}
return Block { nullptr, 0, allocator };
}
inline bool writeToFile(const char *path, Block &block, u64 elementsToWrite = 0, FileMode mode = FILE_BINARY) {
aassert(block.isValid(), "trying to write to a file from an invalid memory block");
u64 count = block.size();
aassert(count >= elementsToWrite, "trying to write more elements than stored in the memory holder");
FILE *file = nullptr;
const char *writeMode = "wb";
if (mode == FILE_TEXT) writeMode = "w";
if ((file = std::fopen(path, writeMode)) != nullptr) {
u64 elementCount = count;
if (elementsToWrite != 0) {
elementCount = elementsToWrite;
}
std::fwrite((void *) block, sizeof(u8), elementCount, file);
std::fclose(file);
return true;
}
return false;
}
}
}
#endif