-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilepath.cpp
executable file
·94 lines (76 loc) · 1.98 KB
/
filepath.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
#include <ostream>
#include <iostream>
#include "filepath.h"
#define OS_SEPARATOR '/'
using namespace std;
const char* getHome() {
const char* home = getenv("HOME");
if (home == nullptr) {
throw "Could not find \"home\" with getenv";
}
return home;
}
file_path::file_path(const char* path) {
if (path[0] == '~') {
// it is at home.
add(getHome());
if (path[1] != '\0') {
// TODO: Check if path[1] is a path separator indeed
// there is more to the path afterwards.
add(&path[2]);
}
} else {
add(path);
}
}
file_path::~file_path() {
}
void file_path::append(const char* component) {
add(component);
valid = false;
}
void file_path::add(const char* path) {
// find all OS_SEPARATOR from the path.
const char* offset = path;
size_t length = 0;
while (offset[length] != '\0') {
switch (offset[length]) {
case '\\':
case '/':
// create a string from the start of the char*
components.push_back(string(offset, length));
// reset the current length
offset = &offset[length + 1];
length = 0;
break;
default:
length++;
break;
}
}
if (length > 0) {
components.push_back(string(offset, length));
}
}
const char* file_path::toString() {
if (!valid) {
valid = true;
s.clear();
for (string& c : components) {
s += c;
s += OS_SEPARATOR;
}
// remove the last slash
s.resize(s.length() - 1);
}
return s.c_str();
}
void file_path::debug() {
for (string& s : components) {
cout << "component: " << s << endl;
}
}
void file_path::removeLast() {
components.pop_back();
valid = false;
}