-
Notifications
You must be signed in to change notification settings - Fork 1
/
abspath_simplify.cc
74 lines (70 loc) · 1.72 KB
/
abspath_simplify.cc
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
/* Qunar 2014 Campus Hiring
*
* 网上题目,注意甄别。
*
* Problem Description:
*
* 将绝对路径转换成相对路径。例如
* input: /home/news/../tmp/game/../
* ouptut: /home/tmp/
*
* Analysis:
*
* 注意:/..与/.与/等价。另外,转换后的并非相对路径。确切地说,
* 应该为:绝对路径简化。
*
*/
#include <iostream>
using std::cout; using std::cerr; using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
static void process_entry(vector<string> &svec, string &entry) {
if(!entry.empty() && entry != ".") {
if (entry == "..") {
if(svec.size() != 0)
svec.pop_back();
} else
svec.push_back(entry);
}
}
string abs_path_conv(const string &s) {
string::size_type prev, cur;
const char delim = '/';
if(s.front() != delim)
return "";
prev = 1;
vector<string> svec;
while( (cur = s.find(delim, prev)) != string::npos) {
string entry = s.substr(prev, cur-prev);
process_entry(svec, entry);
prev = cur + 1;
}
if(prev < s.size()) {
string entry = s.substr(prev);
process_entry(svec, entry);
}
string ret;
if(svec.size() == 0)
ret = "/";
else {
for(auto entry: svec)
ret += "/" + entry;
}
return ret;
}
int main(int argc, char *argv[]) {
if(argc != 2) {
cout << "Usage: " << argv[0] << " <pathname>" << endl;
return -1;
}
string s = abs_path_conv(argv[1]);
if (s.empty()) {
cerr << "The pathname " << argv[1]
<< " is not absolute." << endl;
return -1;
}
cout << s << endl;
return 0;
}