diff --git a/src/Directory.cpp b/src/Directory.cpp index b0fe58bc4..212b7cfd4 100644 --- a/src/Directory.cpp +++ b/src/Directory.cpp @@ -142,6 +142,35 @@ std::vector Directory::listRecursive () return files; } +//////////////////////////////////////////////////////////////////////////////// +std::string Directory::cwd () +{ + char buf[PATH_MAX]; + getcwd (buf, PATH_MAX - 1); + return std::string (buf); +} + +//////////////////////////////////////////////////////////////////////////////// +bool Directory::up () +{ + if (_data == "/") + return false; + + std::string::size_type slash = _data.rfind ('/'); + if (slash == 0) + { + _data = "/"; // Root dir should retain the slash. + return true; + } + else if (slash != std::string::npos) + { + _data = _data.substr (0, slash); + return true; + } + + return false; +} + //////////////////////////////////////////////////////////////////////////////// void Directory::list ( const std::string& base, diff --git a/src/Directory.h b/src/Directory.h index de812ec3e..f3b21d2ae 100644 --- a/src/Directory.h +++ b/src/Directory.h @@ -49,6 +49,9 @@ public: std::vector list (); std::vector listRecursive (); + static std::string cwd (); + bool up (); + private: void list (const std::string&, std::vector &, bool); bool remove_directory (const std::string&); diff --git a/test/directory.t.cpp b/test/directory.t.cpp index ea1173b94..08e0dbd87 100644 --- a/test/directory.t.cpp +++ b/test/directory.t.cpp @@ -35,7 +35,7 @@ Context context; int main (int argc, char** argv) { - UnitTest t (25); + UnitTest t (35); // Directory (const File&); // Directory (const Path&); @@ -104,6 +104,22 @@ int main (int argc, char** argv) t.ok (d7.remove (), "Directory::remove /tmp/to_be_removed"); t.notok (d7.exists (), "Directory /tmp/to_be_removed gone"); + // static std::string cwd (); + std::string cwd = Directory::cwd (); + t.ok (cwd.length () > 0, "Directory::cwd returned a value"); + + // bool parent (std::string&) const; + Directory d9 ("/one/two/three/four.txt"); + t.ok (d9.up (), "parent /one/two/three/four.txt --> true"); + t.is (d9._data, "/one/two/three", "parent /one/two/three/four.txt --> /one/two/three"); + t.ok (d9.up (), "parent /one/two/three --> true"); + t.is (d9._data, "/one/two", "parent /one/two/three --> /one/two"); + t.ok (d9.up (), "parent /one/two --> true"); + t.is (d9._data, "/one", "parent /one/two --> /one"); + t.ok (d9.up (), "parent /one --> true"); + t.is (d9._data, "/", "parent /one --> /"); + t.notok (d9.up (), "parent / --> false"); + return 0; }