16 Path::Path(
const string& path) {
20 char buf[FILENAME_MAX];
22 getcwd(buf, FILENAME_MAX);
24 _getcwd(buf, FILENAME_MAX);
28 Path Path::resolve()
const {
29 if (is_empty())
return *
this;
33 ret = Path::cwd() + *
this;
38 auto parts = split(ret.m_path,
'/');
39 for (
int i = parts.size()-1; i >= 0; i--) {
40 auto& part = parts[i];
41 if ((part.empty() || part ==
".") && i != 0) {
42 parts.erase(parts.begin() + i);
43 }
else if (part ==
".." && i >= 1) {
44 parts.erase(parts.begin() + i);
45 parts.erase(parts.begin() + i - 1);
49 for (
auto& part : parts) ret.m_path += part +
"/";
50 ret.m_path.resize(ret.m_path.size()-1);
54 Path Path::parent()
const {
57 int pos = ret.m_path.rfind(
"/", ends_with(ret.m_path,
"/") ? ret.m_path.size()-2 : string::npos);
58 ret.m_path.resize(pos);
59 }
while (ret.m_path.back() ==
'/');
62 string Path::file_name(
bool extension)
const {
63 int pos = m_path.rfind(
'/');
64 string end = m_path.substr(pos+1);
65 if (extension)
return end;
67 return end.substr(0, pos);
69 bool Path::exists()
const {
72 return stat(m_path.c_str(), &s) == 0;
74 return GetFileAttributes(m_path.c_str()) != INVALID_FILE_ATTRIBUTES;
77 bool Path::is_file()
const {
79 return exists() && !is_directory();
81 bool Path::is_directory()
const {
84 if (stat(m_path.c_str(), &s) == 0) {
85 return s.st_mode & S_IFDIR;
90 return GetFileAttributes(m_path.c_str()) & FILE_ATTRIBUTE_DIRECTORY;
93 bool Path::is_absolute()
const {
94 if (m_path.empty())
return false;
95 int pos = m_path.find(
'/');
96 string root = m_path.substr(0, pos);
97 return root.empty() || (root.size() == 2 && root[1] ==
':');
99 bool Path::operator==(
const char* p)
const {
100 return trim(m_path,
"/\\") ==
trim(p,
"/\\") ? true : resolve().m_path == Path(p).
resolve().m_path;
102 Path Path::operator+(
const char* p)
const {
104 return ends_with(m_path,
"/") ? Path(m_path + p2.m_path) :
105 Path(m_path +
"/" + p2.m_path);
107 Path::iterator Path::begin()
const {
109 ret.set_begin(SetBeginEndKey());
112 Path::iterator Path::end()
const {
114 ret.set_end(SetBeginEndKey());
118 ostream& operator<<(ostream& out,
const Path& path) {
119 return out<<path.to_string();