From 58a766374f1ca750017c25c983d5ee64f6263efe Mon Sep 17 00:00:00 2001 From: wmayer Date: Sat, 19 Mar 2022 13:56:06 +0100 Subject: [PATCH] Base: add method FileInfo::createDirectories() to also create parent directories of a given path --- src/Base/FileInfo.cpp | 36 ++++++++++++++++++++++++++++++++++++ src/Base/FileInfo.h | 7 +++++++ 2 files changed, 43 insertions(+) diff --git a/src/Base/FileInfo.cpp b/src/Base/FileInfo.cpp index 1413a419ac..381bbc9711 100644 --- a/src/Base/FileInfo.cpp +++ b/src/Base/FileInfo.cpp @@ -28,6 +28,7 @@ # include # include # include +# include # if defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) # include # include @@ -190,6 +191,27 @@ std::string FileInfo::getTempFileName(const char* FileName, const char* Path) #endif } +boost::filesystem::path FileInfo::stringToPath(const std::string& str) +{ +#if defined(FC_OS_WIN32) + std::wstring_convert> converter; + boost::filesystem::path path(converter.from_bytes(str)); +#else + boost::filesystem::path path(str); +#endif + return path; +} + +std::string FileInfo::pathToString(const boost::filesystem::path& p) +{ +#if defined(FC_OS_WIN32) + std::wstring_convert> converter; + return converter.to_bytes(p.wstring()); +#else + return p.string(); +#endif +} + void FileInfo::setFile(const char* name) { if (!name) { @@ -512,6 +534,20 @@ bool FileInfo::createDirectory() const #endif } +bool FileInfo::createDirectories() const +{ + try { + boost::filesystem::path path(stringToPath(FileName)); + if (boost::filesystem::exists(path)) + return true; + boost::filesystem::create_directories(path); + return true; + } + catch (const boost::filesystem::filesystem_error&) { + return false; + } +} + bool FileInfo::deleteDirectory() const { if (isDir() == false ) return false; diff --git a/src/Base/FileInfo.h b/src/Base/FileInfo.h index 123b8df753..3cc02239fc 100644 --- a/src/Base/FileInfo.h +++ b/src/Base/FileInfo.h @@ -25,6 +25,7 @@ #ifndef BASE_FILEINFO_H #define BASE_FILEINFO_H +#include #include #include #include @@ -116,6 +117,8 @@ public: //@{ /// Creates a directory. Returns true if successful; otherwise returns false. bool createDirectory( ) const; + /// Creates a directory and all its parent directories. Returns true if successful; otherwise returns false. + bool createDirectories() const; /// Get a list of the directory content std::vector getDirectoryContent() const; /// Delete an empty directory @@ -137,6 +140,10 @@ public: static std::string getTempFileName(const char* FileName=nullptr, const char* path=nullptr); /// Get the path to the dir which is considered to temp files static const std::string &getTempPath(); + /// Convert from filesystem path to string + static std::string pathToString(const boost::filesystem::path& p); + /// Convert from string to filesystem path + static boost::filesystem::path stringToPath(const std::string& str); //@} protected: