-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.cpp
66 lines (57 loc) · 1.47 KB
/
util.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
#include "util.h"
using namespace std;
void throw_error(string s){
throw "Error: "+s;
}
vector<string> split(const string &s, const char delim, int numsplits) {
string::size_type cursor = 0;
string::size_type idx = s.find(delim);
vector<string> vec;
while (idx != string::npos && numsplits != 0) {
vec.push_back(s.substr(cursor, idx - cursor));
numsplits--;
cursor = idx + 1;
idx = s.find(delim, cursor);
}
vec.push_back(s.substr(cursor, string::npos));
return vec;
}
void readFile(const char* const filePath, function<void(string)> func) {
ifstream f(filePath);
if (!!f) {
string line;
while (f) {
getline(f, line);
func(line);
}
} else {
char *message;
asprintf(&message, "Can't read file '%s'. Does it exist?", filePath);
throw message;
}
}
string joinVector(const vector<string> &vect, const string &seperator) {
string s;
for (int i = 0; i < (int)vect.size(); i++) {
s += vect[i];
if (i != (int)vect.size() - 1) s += seperator;
}
return s;
}
string joinVector(const vector<string> &vect, char seperator) {
return joinVector(vect, string(1, seperator));
}
Maybe<vector<dirEntry>> readDir(const string &dirname) {
vector<dirEntry> result;
DIR *dir = opendir(dirname.c_str());
if (dir == NULL) return Nothing();
dirent *item = readdir(dir);
while (item != NULL) {
dirEntry entry;
entry.name = string(item->d_name);
entry.type = static_cast<dirEntryType>(item->d_type);
result.push_back(entry);
item = readdir(dir);
}
return result;
}