-
Notifications
You must be signed in to change notification settings - Fork 3
/
OSUtils.cpp
95 lines (80 loc) · 2.05 KB
/
OSUtils.cpp
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 "OSUtils.h"
#include <array>
#include <string>
#include <stdexcept>
#include <memory>
#include <fstream>
#include <sys/stat.h>
#include <cstring>
#include <limits.h>
#include <errno.h>
#include <iomanip>
int mkdir_p(const char *path)
{
/* Adapted from http://stackoverflow.com/a/2336245/119527 */
const size_t len = strlen(path);
char _path[PATH_MAX];
char *p;
errno = 0;
/* Copy string so its mutable */
if (len > sizeof(_path)-1) {
errno = ENAMETOOLONG;
return -1;
}
strcpy(_path, path);
/* Iterate the string */
for (p = _path + 1; *p; p++) {
if (*p == '/') {
/* Temporarily truncate */
*p = '\0';
if (mkdir(_path, S_IRWXU) != 0) {
if (errno != EEXIST)
return -1;
}
*p = '/';
}
}
if (mkdir(_path, S_IRWXU) != 0) {
if (errno != EEXIST)
return -1;
}
return 0;
}
std::string ExecuteShell(const std::string& cmd)
{
std::cout << cmd << std::endl;
std::array<char, 128> buffer;
std::string result;
std::shared_ptr<FILE> pipe(popen(cmd.c_str(), "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
result += buffer.data();
}
return result;
}
void MakeCleanDir(const std::string& dir)
{
mkdir_p(dir.c_str());
}
void MoveDirectory(const std::string& from, const std::string& to)
{
ExecuteShell("rm -rf " + to);
ExecuteShell("mv " + from + " " + to);
}
bool FileExists(const std::string& filename)
{
std::ifstream file(filename, std::ios::in | std::ios::binary);
return file.good();
}
void SaveValueToFile(stratifloat value, const std::string& filename)
{
std::ofstream paramFile(filename);
paramFile << std::setprecision(30);
paramFile << value;
}
void LoadValueFromFile(stratifloat& value, const std::string& filename)
{
std::ifstream paramFile(filename);
paramFile >> value;
}