-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.cpp
More file actions
111 lines (96 loc) · 2.23 KB
/
utils.cpp
File metadata and controls
111 lines (96 loc) · 2.23 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//
// Created by Ian Parker on 24/06/2025.
//
#include "utils.h"
using namespace std;
bool shouldTrim(unsigned char ch)
{
return std::isspace(ch) || std::iscntrl(ch);
}
void ltrim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !shouldTrim(ch);
}));
}
void rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !shouldTrim(ch);
}).base(), s.end());
}
void trim(std::string &s)
{
rtrim(s);
ltrim(s);
}
vector<string> splitString(string line, char splitChar)
{
vector<string> parts;
while (!line.empty())
{
size_t pos = line.find(splitChar);
if (pos == string::npos)
{
pos = line.length();
if (pos == 0)
{
break;
}
}
if (pos >= 1)
{
string part = line.substr(0, pos);
trim(part);
parts.push_back(part);
}
if (pos == line.length())
{
break;
}
line = line.substr(pos + 1);
}
return parts;
}
std::string joinToEnd(vector<string> parts, int startPos)
{
std::string result;
for (unsigned int i = startPos; i < parts.size(); i++)
{
if (!result.empty())
{
result += " ";
}
result += parts.at(i);
}
return result;
}
vector<Line> readTextFile(const string& filename, bool split)
{
vector<Line> result;
FILE* fd = fopen(filename.c_str(), "r");
if (fd == nullptr)
{
fprintf(stderr, "readTextFile: Failed to open file %s\n", filename.c_str());
return result;
}
char lineBuffer[2048];
while (fgets(lineBuffer, 2048, fd) != nullptr)
{
Line line;
line.line = lineBuffer;
// Skip UTF-8 BOM
if (line.line.length() >= 3 && (uint8_t)line.line.at(0) == 0xef && (uint8_t)line.line.at(1) == 0xbb && (uint8_t)line.line.at(2) == 0xbf)
{
line.line = line.line.substr(3);
}
trim(line.line);
if (split)
{
line.tokens = splitString(line.line, ':');
}
result.push_back(line);
}
fclose(fd);
return result;
}