C++ Utils
0.1
|
00001 00037 #ifndef UTILS_PATH_H 00038 #define UTILS_PATH_H 00039 00040 #include <string> 00041 #include <sys/stat.h> 00042 00043 #include "utils/stringutils.h" 00044 00045 namespace utils 00046 { 00047 00051 class Path 00052 { 00053 private: 00054 std::string m_path; 00055 00056 public: 00057 Path() 00058 { 00059 } 00060 00061 Path(const char* path) 00062 : m_path(path) 00063 { 00064 init(); 00065 } 00066 00067 Path(const std::string &path) 00068 : m_path(path) 00069 { 00070 init(); 00071 } 00072 00076 operator std::string() const 00077 { 00078 return m_path; 00079 } 00080 00084 std::string basename() const 00085 { 00086 const size_t lastSlash = m_path.find_last_of(separators()); 00087 if (lastSlash == std::string::npos) 00088 return m_path; 00089 00090 return m_path.substr(lastSlash+1); 00091 } 00092 00096 std::string dirname() const 00097 { 00098 const size_t lastSlash = m_path.find_last_of(separators()); 00099 if (lastSlash == std::string::npos) 00100 return ""; 00101 00102 return m_path.substr(0, lastSlash); 00103 } 00104 00108 Path dir() const 00109 { 00110 return Path(dirname()); 00111 } 00112 00116 bool exists() const 00117 { 00118 struct stat buffer; 00119 return (stat(m_path.c_str(), &buffer) == 0); 00120 } 00121 00128 Path operator+(const Path& other) const 00129 { 00130 if (m_path.empty()) 00131 return other; 00132 if (other.m_path.empty()) 00133 return *this; 00134 00135 return Path(m_path + SEPARATOR + other.m_path); 00136 } 00137 00138 public: 00139 static const char* separator() 00140 { 00141 static const std::string sep(1, SEPARATOR); 00142 return sep.c_str(); 00143 } 00144 00148 static const char* separators() 00149 { 00150 #if __unix__ 00151 return "/"; 00152 #else // __unix__ 00153 return "\\/"; 00154 #endif // __unix__ 00155 } 00156 00157 private: 00158 void init() 00159 { 00160 // Remove trailing separator 00161 if (StringUtils::endsWith(m_path, separator())) 00162 StringUtils::replaceLast(m_path, separator(), ""); 00163 } 00164 00165 public: 00166 #ifdef __unix__ 00167 static const char SEPARATOR = '/'; 00168 #else // __unix__ 00169 static const char SEPARATOR = '\\'; 00170 #endif // __unix__ 00171 00172 }; 00173 00174 } 00175 00176 #endif // UTILS_PATH_H