-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.h
77 lines (62 loc) · 1.51 KB
/
file.h
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
#pragma once
#include <json.h>
#include <sys/stat.h>
#include <string>
#include <string_view>
namespace file
{
inline std::string get_data_root()
{
static auto root = []() -> std::string
{
auto root_env = std::getenv("DATA_ROOT");
if (!root_env)
return {};
return std::string(root_env) + "/";
}();
return root;
}
inline bool does_file_exist(std::string filename)
{
if (filename.find(get_data_root()) == filename.npos)
filename = get_data_root() + filename;
struct stat temp;
return stat(filename.c_str(), &temp) == 0;
}
inline std::string read_file(std::string filename)
{
if (filename.find(get_data_root()) == filename.npos)
filename = get_data_root() + filename;
if (!file::does_file_exist(filename))
return {};
auto file = fopen(filename.c_str(), "r");
fseek(file, 0, SEEK_END);
auto file_len = ftell(file);
rewind(file);
std::string buffer;
buffer.resize(file_len);
fread(buffer.data(), 1, file_len, file);
fclose(file);
return buffer;
}
inline nlohmann::basic_json<> read_json_file(const std::string &filename)
{
auto file = read_file(filename);
try
{
return nlohmann::json::parse(file);
}
catch (nlohmann::json::exception)
{
}
return nlohmann::json();
}
inline void write_file(std::string filename, std::string_view content)
{
if (filename.find(get_data_root()) == filename.npos)
filename = get_data_root() + filename;
auto file = fopen(filename.c_str(), "w");
fwrite(content.data(), 1, content.size(), file);
fclose(file);
}
}