Base: add method FileInfo::createDirectories() to also create parent directories of a given path

This commit is contained in:
wmayer
2022-03-19 13:56:06 +01:00
parent 2ad512f14b
commit a817a68c17
2 changed files with 43 additions and 0 deletions

View File

@@ -28,6 +28,7 @@
# include <algorithm>
# include <cassert>
# include <cstring>
# include <locale>
# if defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD)
# include <dirent.h>
# include <unistd.h>
@@ -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<std::codecvt_utf8_utf16<wchar_t>> 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<std::codecvt_utf8_utf16<wchar_t>> 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;

View File

@@ -25,6 +25,7 @@
#ifndef BASE_FILEINFO_H
#define BASE_FILEINFO_H
#include <boost/filesystem.hpp>
#include <string>
#include <vector>
#include <Base/TimeInfo.h>
@@ -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<Base::FileInfo> 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: