Kaynağa Gözat

Extended File class

- added "renameTo" method to File class
- added tests for File class
Patrick 4 yıl önce
ebeveyn
işleme
a7acd062ed
3 değiştirilmiş dosya ile 38 ekleme ve 0 silme
  1. 18 0
      source/io/File.cpp
  2. 2 0
      source/io/File.hpp
  3. 18 0
      test/cases/io/FileTest.cpp

+ 18 - 0
source/io/File.cpp

@@ -15,6 +15,7 @@
 #include <algorithm>
 #include <sstream>
 #include <vector>
+#include <cstdio>
 
 #if defined(unix) || defined(__APPLE__)
 #include <unistd.h>
@@ -175,6 +176,18 @@ void ls_std::File::remove()
     }
   }
 }
+
+bool ls_std::File::renameTo(const std::string &_newName)
+{
+  bool renamed = ls_std::File::_renameTo(this->absoluteFilePath, _newName);
+
+  if(renamed) {
+    this->absoluteFilePath = _newName;
+  }
+
+  return renamed;
+}
+
 #ifdef _WIN32
 void ls_std::File::_addToFileListWindows(const std::string& _path, bool _withDirectories, WIN32_FIND_DATA _data, std::list<std::string>& _list)
 {
@@ -358,6 +371,11 @@ std::string ls_std::File::_normalizePath(std::string _path)
   return _path;
 }
 
+bool ls_std::File::_renameTo(const std::string &_oldName, const std::string &_newName)
+{
+  return std::rename(_oldName.c_str(), _newName.c_str()) == 0;
+}
+
 std::vector<std::string> ls_std::File::_splitIntoSubDirectoryNames(const std::string& _path) {
   std::vector<std::string> subDirectoryNames {};
   std::stringstream _stream {_path};

+ 2 - 0
source/io/File.hpp

@@ -53,6 +53,7 @@ namespace ls_std {
       void makeDirectory();
       void makeDirectories();
       void remove();
+      bool renameTo(const std::string& _newName);
 
     private:
 
@@ -79,6 +80,7 @@ namespace ls_std {
       #endif
       static int _mkdir(const std::string& _path);
       static std::string _normalizePath(std::string _path);
+      static bool _renameTo(const std::string& _oldName, const std::string& _newName);
       static std::vector<std::string> _splitIntoSubDirectoryNames(const std::string& _path);
   };
 }

+ 18 - 0
test/cases/io/FileTest.cpp

@@ -247,4 +247,22 @@ namespace {
     directory = ls_std::File(TestHelper::getResourcesFolderLocation() + "testDir");
     directory.remove();
   }
+
+  TEST_F(FileTest, renameTo)
+  {
+    std::string currentName = TestHelper::getResourcesFolderLocation() + "tmp_rename_to.txt";
+    std::string newName = TestHelper::getResourcesFolderLocation() + "tmp_rename_to_better_name.txt";
+
+    ls_std::File file {currentName};
+    file.createNewFile();
+
+    ASSERT_TRUE(file.exists());
+    ASSERT_STREQ(currentName.c_str(), file.getAbsoluteFilePath().c_str());
+
+    file.renameTo(newName);
+    ASSERT_TRUE(file.exists());
+    ASSERT_STREQ(newName.c_str(), file.getAbsoluteFilePath().c_str());
+
+    file.remove();
+  }
 }