Bläddra i källkod

Extended File class (incomplete)

- added "canWrite" method to File class (Windows
implementation pending / not tested)
- added test for File class
patrickmattulat 3 år sedan
förälder
incheckning
ac8b9f0c44
4 ändrade filer med 35 tillägg och 0 borttagningar
  1. 20 0
      source/io/File.cpp
  2. 2 0
      source/io/File.hpp
  3. 12 0
      test/cases/io/FileTest.cpp
  4. 1 0
      test/resources/no_writable.txt

+ 20 - 0
source/io/File.cpp

@@ -57,6 +57,11 @@ bool ls_std::File::canRead()
   return readable;
 }
 
+bool ls_std::File::canWrite()
+{
+  return ls_std::File::_isWritable(this->absoluteFilePath);
+}
+
 void ls_std::File::createNewFile()
 {
   if(!ls_std::File::_exists(this->absoluteFilePath)) {
@@ -323,6 +328,21 @@ bool ls_std::File::_isReadableWindows(const std::string &_path)
 }
 #endif
 
+bool ls_std::File::_isWritable(const std::string &_path)
+{
+  bool writable {};
+
+  if(ls_std::File::_exists(_path)) {
+    struct stat _stat {};
+
+    if(stat(_path.c_str(), &_stat) == 0) {
+      writable = (_stat.st_mode & (unsigned) S_IWRITE) != 0;
+    }
+  }
+
+  return writable;
+}
+
 time_t ls_std::File::_lastModified(const std::string &_path)
 {
   time_t lastModifiedTimeStamp {};

+ 2 - 0
source/io/File.hpp

@@ -41,6 +41,7 @@ namespace ls_std {
 
       bool canExecute();
       bool canRead();
+      bool canWrite();
       void createNewFile();
       bool exists();
       std::string getAbsoluteFilePath();
@@ -78,6 +79,7 @@ namespace ls_std {
       #ifdef _WIN32
         static bool _isReadableWindows(const std::string& _path);
       #endif
+      static bool _isWritable(const std::string& _path);
       static time_t _lastModified(const std::string& _path);
       static std::list<std::string> _list(const std::string& _path);
       static std::list<std::string> _listFiles(const std::string& _path);

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

@@ -76,6 +76,18 @@ namespace {
     ASSERT_TRUE(readableFile.canRead());
   }
 
+  TEST_F(FileTest, canWrite)
+  {
+    ls_std::File readableFile {this->fileLocation};
+    ASSERT_TRUE(readableFile.canWrite());
+  }
+
+  TEST_F(FileTest, canWriteNegative)
+  {
+    ls_std::File noWritableFile {TestHelper::getResourcesFolderLocation() + "no_writable.txt"};
+    ASSERT_FALSE(noWritableFile.canWrite());
+  }
+
   TEST_F(FileTest, createNewFileAndRemove)
   {
     ls_std::File file {TestHelper::getResourcesFolderLocation() + "tmp.txt"};

+ 1 - 0
test/resources/no_writable.txt

@@ -0,0 +1 @@
+Hello!