6 #ifndef UTILS_FILESYSTEM_H 7 #define UTILS_FILESYSTEM_H 15 #include <experimental/filesystem> 22 #include <Utils/ExtSTD.h> 23 #include "FileTypes.h" 35 return (stat(filename, &info) == 0 && !(info.st_mode & S_IFDIR));
45 inline bool FileCopy(
const std::string &src,
const std::string &dest)
47 std::ifstream orig(src, std::ios::binary);
48 std::ofstream copy(dest, std::ios::binary);
49 if (!orig.good() || !copy.good())
58 inline bool FileRename(
const std::string &src_file,
const std::string &new_name)
60 return std::rename(src_file.c_str(), new_name.c_str());
66 return std::remove(file.c_str()) == 0;
79 if (stat(dir_path.c_str(), &info) != 0)
85 return (info.st_mode & S_IFDIR);
98 return std::experimental::filesystem::create_directory(dir_path);
110 return std::experimental::filesystem::create_directories(dir_path);
114 inline bool RemoveDir(
const std::string &dir_path,
bool recursive =
true)
118 return std::experimental::filesystem::remove_all(dir_path) > 0u;
120 return std::experimental::filesystem::remove(dir_path);
126 const auto startpos = filename.find_first_of(
".", filename.find_last_of(R
"(/\)") + 1) + 1; 127 const auto endpos = filename.length();
128 const auto ext = filename.substr(startpos, endpos - startpos);
133 inline bool HasExtenstion(
const std::string &filename,
const std::string &extenstion)
135 const auto f_result = filename.rfind(extenstion);
136 return (f_result != std::string::npos && f_result == (filename.size() - extenstion.size()));
146 inline bool IsFileType(
const std::string &filename,
const std::vector<file_types::Type> &types)
154 std::ifstream ifs(file_name);
157 std::string contents;
158 std::getline(ifs, contents, (
char)ifs.eof());
165 inline void StringToFile(
const std::string &file_name,
const std::string &str)
168 file.open(file_name);
175 template <
typename T>
178 std::ifstream ifs(file_name);
181 std::vector<T> values;
187 if (values.size() == values.capacity())
189 values.reserve(values.size() * 2);
191 values.push_back(value);
210 inline void ListDirectoryContentsRecursive(
const std::string &direcory_path, uint32_t depth, std::vector<FileDirContent> *results)
212 for (
auto &p : std::experimental::filesystem::directory_iterator(direcory_path.c_str()))
214 FileDirContent item(p.path().filename().string(), p.status().type() == std::experimental::filesystem::file_type::directory);
215 item.
full_path = direcory_path + item.name;
217 if (item.is_directory && (item.name ==
"." || item.name ==
".."))
222 if (results->size() == results->capacity())
224 results->reserve(results->capacity() * 2);
227 results->push_back(item);
228 if (depth > 0 && item.is_directory)
230 ListDirectoryContentsRecursive(item.full_path +
'/', depth - 1, results);
239 std::vector<FileDirContent> results;
242 direcory_path.erase(direcory_path.find_last_not_of(
"\\/") + 1, std::string::npos);
243 direcory_path +=
'/';
245 ListDirectoryContentsRecursive(direcory_path, (recursive) ? UINT32_MAX : 0, &results);
251 inline std::vector<std::string>
ListDirectoryFileNames(
const std::string &direcory_path,
const std::string &extension =
"")
254 std::vector<std::string> result;
255 result.reserve(content.size());
257 for (
auto &item : content)
259 if (!item.is_directory)
261 if (extension.empty() ||
HasExtenstion(item.name, extension))
263 result.emplace_back(item.name);
267 result.shrink_to_fit();
275 const auto ext = file_types::GetExt(file_type);
286 std::vector<std::string> result;
288 for (
const auto &file_type : file_types)
291 result.insert(result.end(), file_type_file_names.begin(), file_type_file_names.end());
312 auto pos = file_name_with_path.find_last_of(R
"(/\)"); 313 return (pos != std::string::npos) ? file_name_with_path.substr(0, pos) :
"";
317 inline std::string
GetFileName(
const std::string &file_name_with_path,
bool strip_extension =
false)
319 auto startpos = file_name_with_path.find_last_of(R
"(/\)") + 1; 320 auto endpos = file_name_with_path.length();
323 endpos = file_name_with_path.find_first_of(
".", startpos);
325 return file_name_with_path.substr(startpos, endpos - startpos);
331 return std::experimental::filesystem::absolute(local_path.c_str()).
string();
340 inline std::string
Execute(
const char *command,
const size_t buffer_size = 128)
342 std::vector<char> buffer(buffer_size);
345 std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(command,
"r"), _pclose);
347 std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command,
"r"), pclose);
349 #error "platform not supported" 353 throw std::runtime_error(
"popen() failed!");
355 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe.get()) !=
nullptr)
357 result += buffer.data();
363 inline int RunExe(
const std::string &exe_path,
const std::string &cmd_arguments =
"")
368 PROCESS_INFORMATION pi;
371 ZeroMemory(&si,
sizeof(si));
373 ZeroMemory(&pi,
sizeof(pi));
379 CreateProcess(exe_pathW.c_str(),
380 const_cast<wchar_t *
>((exe_pathW + L
" " + cmd_argumentsW).c_str()),
391 WaitForSingleObject(pi.hProcess, INFINITE);
395 const bool is_exit_code = GetExitCodeProcess(pi.hProcess, &exitCode);
396 const int commandReturnValue = is_exit_code ?
static_cast<int>(exitCode) : -1;
399 CloseHandle(pi.hProcess);
400 CloseHandle(pi.hThread);
402 return commandReturnValue;
405 const int commandReturnValue = (exe_path[0] ==
'/')
406 ? system((exe_path +
" " + cmd_arguments).c_str())
407 : system((
"./" + exe_path +
" " + cmd_arguments).c_str());
409 if (commandReturnValue < 0)
411 std::cout <<
"Command: " << exe_path <<
" " << cmd_arguments <<
" failed." << std::endl;
413 return commandReturnValue;
415 #error "platform not supported" 426 const auto endpos = file_name_with_extension.find_first_of(
".", 0);
427 return file_name_with_extension.substr(0, endpos);
439 inline bool FileExistsInDirectory(
const std::string &dir_path,
const std::string &filename,
bool strip_extension =
false)
448 return filename == file_in_directory;
std::string Lowercase(const std::string &text)
Converts text into all lowercase.
Definition: ExtSTD.h:311
void StringToFile(const std::string &file_name, const std::string &str)
Exports the string to a text file.
Definition: Filesystem.h:165
bool DirectoryContainsAny(const std::string &direcory_path, const file_types::Type file_type)
Checks specified directory if it contains file(s) of specified type.
Definition: Filesystem.h:298
auto AnyOf(const C &container, const P &Predicate) -> bool
Simplified wrapper for std::any_of.
Definition: ExtSTD.h:849
std::vector< T > FileToVector(const std::string &file_name)
Loads contents of a text-based file and stores it in a vector. The file must contain only elements of...
Definition: Filesystem.h:176
bool FileRename(const std::string &src_file, const std::string &new_name)
Changes name of a source file to a new name.
Definition: Filesystem.h:58
bool FileExistsInDirectory(const std::string &dir_path, const std::string &filename, bool strip_extension=false)
Checks whether a specified file exists in directory.
Definition: Filesystem.h:439
std::vector< FileDirContent > ListDirectoryContents(std::string direcory_path, const bool recursive=false)
Returns list of all contents in a specified directory.
Definition: Filesystem.h:237
bool CreateDirHierarchy(const std::string &dir_path)
Creates a specified directory hierarchy.
Definition: Filesystem.h:108
bool DirectoryExists(const std::string &dir_path)
Checks whether a specified directory exists. May contain the last slash but is not required...
Definition: Filesystem.h:70
An essential interface for manipulation with files and directories. Wraps file managing system calls...
Definition: Filesystem.h:28
std::string GetAbsolutePath(const std::string &local_path)
Retrieves full system path to a specified local file or directory. Specified local path may contain n...
Definition: Filesystem.h:329
std::wstring ToWString(const std::string &text)
Convert single-byte std::string to std::wstring.
Definition: ExtSTD.h:68
std::string GetDirectoryPathOfFile(const std::string &file_name_with_path)
Takes specified file path and strips everything after the last directory separator (including the sep...
Definition: Filesystem.h:310
bool is_directory
Entry name. If file, contains also file extension.
Definition: Filesystem.h:204
bool FileRemove(const std::string &file)
Deletes a specified file from the system. Deleted file will not appear in recycle bin...
Definition: Filesystem.h:64
Type
Enum class that specifies (geometry) file types that we recognize.
Definition: FileTypes.h:33
int RunExe(const std::string &exe_path, const std::string &cmd_arguments="")
Runs executable in command line.
Definition: Filesystem.h:363
std::string FileToString(const std::string &file_name)
Loads contents of a text-based file and stores it in a string.
Definition: Filesystem.h:152
std::string GetExtension(const std::string &filename)
Returns string representing file extension, in lower case with no dot.
Definition: Filesystem.h:124
bool IsFileType(const std::string &filename, const file_types::Type type)
Checks whether the file is of a specified type.
Definition: Filesystem.h:140
std::string Execute(const char *command, const size_t buffer_size=128)
Executes command as if it was called from the command line.
Definition: Filesystem.h:340
bool RemoveDir(const std::string &dir_path, bool recursive=true)
Removes input directory if it is empty or if recursive is set to true.
Definition: Filesystem.h:114
Definitions and functions for file types supported by codebase.
Definition: FileTypes.h:17
void SortAndRemoveDuplicates(std::vector< Type > &vec)
Sorts the array and removes duplicate elements.
Definition: ExtSTD.h:422
bool FileCopy(const std::string &src, const std::string &dest)
Makes a copy of a source file to a destination file. Destination directory must exist.
Definition: Filesystem.h:45
std::vector< std::string > ListDirectoryFileNames(const std::string &direcory_path, const std::string &extension="")
Returns list of all file contents in a specified directory (ignores directories). Providing extension...
Definition: Filesystem.h:251
std::string full_path
Whether entry is directory.
Definition: Filesystem.h:205
bool FileExists(const char *filename)
Checks if the specified file exist.
Definition: Filesystem.h:32
Information about single system directory entry.
Definition: Filesystem.h:200
bool HasExtenstion(const std::string &filename, const std::string &extenstion)
Checks whether the file has a specific extension. An extension parameter is case sensitive and can be...
Definition: Filesystem.h:133
bool CreateDir(const std::string &dir_path)
Creates a specified directory.
Definition: Filesystem.h:96
std::string GetFileName(const std::string &file_name_with_path, bool strip_extension=false)
Strips everything before the last directory separator, including the separator. If parameter strip_ex...
Definition: Filesystem.h:317
std::string StripExtension(const std::string &file_name_with_extension)
Strips the extension from a file name.
Definition: Filesystem.h:424