Utilities
Utilities header only library
Filesystem.h
1 /*
2  Copyright (C) Skeletex Research, s.r.o. - All Rights Reserved
3  Unauthorized copying of this file, via any medium is strictly prohibited
4  Proprietary and confidential
5 */
6 #ifndef UTILS_FILESYSTEM_H
7 #define UTILS_FILESYSTEM_H
8 #include <fstream>
9 #include <vector>
10 #include <codecvt>
11 #include <string>
12 #include <string>
13 #include <list>
14 #include <sys/stat.h>
15 #include <experimental/filesystem>
16 
17 #ifdef _WIN32
18 #include <Windows.h>
19 #include <conio.h>
20 #endif // _WIN32
21 
22 #include <Utils/ExtSTD.h>
23 #include "FileTypes.h"
24 
25 
26 
28 namespace fs
29 {
30 
32  inline bool FileExists(const char *filename)
33  {
34  struct stat info;
35  return (stat(filename, &info) == 0 && !(info.st_mode & S_IFDIR));
36  }
37 
39  inline bool FileExists(const std::string &filename)
40  {
41  return FileExists(filename.c_str());
42  }
43 
45  inline bool FileCopy(const std::string &src, const std::string &dest)
46  {
47  std::ifstream orig(src, std::ios::binary);
48  std::ofstream copy(dest, std::ios::binary);
49  if (!orig.good() || !copy.good())
50  {
51  return false;
52  }
53  copy << orig.rdbuf();
54  return true;
55  }
56 
58  inline bool FileRename(const std::string &src_file, const std::string &new_name)
59  {
60  return std::rename(src_file.c_str(), new_name.c_str());
61  }
62 
64  inline bool FileRemove(const std::string &file)
65  {
66  return std::remove(file.c_str()) == 0;
67  }
68 
70  inline bool DirectoryExists(const std::string &dir_path)
71  {
72  if (dir_path.empty())
73  {
74  return true;
75  }
76 
77  struct stat info;
78 
79  if (stat(dir_path.c_str(), &info) != 0)
80  {
81  return false; // cannot access to the directory
82  }
83  else
84  {
85  return (info.st_mode & S_IFDIR);
86  }
87  }
88 
96  inline bool CreateDir(const std::string &dir_path)
97  {
98  return std::experimental::filesystem::create_directory(dir_path);
99  }
100 
108  inline bool CreateDirHierarchy(const std::string &dir_path)
109  {
110  return std::experimental::filesystem::create_directories(dir_path);
111  }
112 
114  inline bool RemoveDir(const std::string &dir_path, bool recursive = true)
115  {
116  if (recursive)
117  {
118  return std::experimental::filesystem::remove_all(dir_path) > 0u;
119  }
120  return std::experimental::filesystem::remove(dir_path);
121  }
122 
124  inline std::string GetExtension(const std::string &filename)
125  {
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);
129  return std_ext::Lowercase(ext);
130  }
131 
133  inline bool HasExtenstion(const std::string &filename, const std::string &extenstion)
134  {
135  const auto f_result = filename.rfind(extenstion);
136  return (f_result != std::string::npos && f_result == (filename.size() - extenstion.size()));
137  }
138 
140  inline bool IsFileType(const std::string &filename, const file_types::Type type)
141  {
142  return HasExtenstion(filename, file_types::GetExt(type));
143  }
144 
146  inline bool IsFileType(const std::string &filename, const std::vector<file_types::Type> &types)
147  {
148  return std_ext::AnyOf(types, [&filename](const auto & type) { return IsFileType(filename, type); });
149  }
150 
152  inline std::string FileToString(const std::string &file_name)
153  {
154  std::ifstream ifs(file_name);
155  if (ifs.good())
156  {
157  std::string contents;
158  std::getline(ifs, contents, (char)ifs.eof());
159  return contents;
160  }
161  return "";
162  }
163 
165  inline void StringToFile(const std::string &file_name, const std::string &str)
166  {
167  std::ofstream file;
168  file.open(file_name);
169  file << str;
170  file.close();
171  }
172 
173 
175  template <typename T>
176  inline std::vector<T> FileToVector(const std::string &file_name)
177  {
178  std::ifstream ifs(file_name);
179  if (ifs.good())
180  {
181  std::vector<T> values;
182  values.reserve(4);
183  while (!ifs.eof())
184  {
185  T value;
186  ifs >> value;
187  if (values.size() == values.capacity())
188  {
189  values.reserve(values.size() * 2);
190  }
191  values.push_back(value);
192  }
193  return values;
194  }
195  return {};
196  }
197 
198 
201  {
202  FileDirContent(const std::string &_name, const bool is_dir) : name(_name), is_directory(is_dir) {};
203  std::string name;
205  std::string full_path;
206  };
207 
208  namespace
209  {
210  inline void ListDirectoryContentsRecursive(const std::string &direcory_path, uint32_t depth, std::vector<FileDirContent> *results)
211  {
212  for (auto &p : std::experimental::filesystem::directory_iterator(direcory_path.c_str()))
213  {
214  FileDirContent item(p.path().filename().string(), p.status().type() == std::experimental::filesystem::file_type::directory);
215  item.full_path = direcory_path + item.name;
216 
217  if (item.is_directory && (item.name == "." || item.name == ".."))
218  {
219  continue;
220  }
221 
222  if (results->size() == results->capacity())
223  {
224  results->reserve(results->capacity() * 2);
225  }
226 
227  results->push_back(item);
228  if (depth > 0 && item.is_directory)
229  {
230  ListDirectoryContentsRecursive(item.full_path + '/', depth - 1, results);
231  }
232  }
233  }
234  }
235 
237  inline std::vector<FileDirContent> ListDirectoryContents(std::string direcory_path, const bool recursive = false)
238  {
239  std::vector<FileDirContent> results;
240  results.reserve(32);
241 
242  direcory_path.erase(direcory_path.find_last_not_of("\\/") + 1, std::string::npos);
243  direcory_path += '/';
244 
245  ListDirectoryContentsRecursive(direcory_path, (recursive) ? UINT32_MAX : 0, &results);
246 
247  return results;
248  }
249 
251  inline std::vector<std::string> ListDirectoryFileNames(const std::string &direcory_path, const std::string &extension = "")
252  {
253  const std::vector<FileDirContent> content = ListDirectoryContents(direcory_path);
254  std::vector<std::string> result;
255  result.reserve(content.size());
256 
257  for (auto &item : content)
258  {
259  if (!item.is_directory)
260  {
261  if (extension.empty() || HasExtenstion(item.name, extension))
262  {
263  result.emplace_back(item.name);
264  }
265  }
266  }
267  result.shrink_to_fit();
269  return result;
270  }
271 
273  inline std::vector<std::string> ListDirectoryFileNames(const std::string &direcory_path, const file_types::Type file_type)
274  {
275  const auto ext = file_types::GetExt(file_type);
276  if (ext.empty())
277  {
278  return {};
279  }
280  return ListDirectoryFileNames(direcory_path, ext);
281  }
282 
284  inline std::vector<std::string> ListDirectoryFileNames(const std::string &direcory_path, const std::vector<file_types::Type> &file_types)
285  {
286  std::vector<std::string> result;
287 
288  for (const auto &file_type : file_types)
289  {
290  const auto file_type_file_names = ListDirectoryFileNames(direcory_path, file_type);
291  result.insert(result.end(), file_type_file_names.begin(), file_type_file_names.end());
292  }
293 
294  return result;
295  }
296 
298  inline bool DirectoryContainsAny(const std::string &direcory_path, const file_types::Type file_type)
299  {
300  return !ListDirectoryFileNames(direcory_path, file_type).empty();
301  }
302 
304  inline bool DirectoryContainsAny(const std::string &direcory_path, const std::vector<file_types::Type> &file_types)
305  {
306  return std_ext::AnyOf(file_types, [&](const auto & file_type)->bool { return !ListDirectoryFileNames(direcory_path, file_type).empty(); });
307  }
308 
310  inline std::string GetDirectoryPathOfFile(const std::string &file_name_with_path)
311  {
312  auto pos = file_name_with_path.find_last_of(R"(/\)");
313  return (pos != std::string::npos) ? file_name_with_path.substr(0, pos) : "";
314  }
315 
317  inline std::string GetFileName(const std::string &file_name_with_path, bool strip_extension = false)
318  {
319  auto startpos = file_name_with_path.find_last_of(R"(/\)") + 1;
320  auto endpos = file_name_with_path.length();
321  if (strip_extension)
322  {
323  endpos = file_name_with_path.find_first_of(".", startpos);
324  }
325  return file_name_with_path.substr(startpos, endpos - startpos);
326  }
327 
329  inline std::string GetAbsolutePath(const std::string &local_path)
330  {
331  return std::experimental::filesystem::absolute(local_path.c_str()).string();
332  }
333 
340  inline std::string Execute(const char *command, const size_t buffer_size = 128)
341  {
342  std::vector<char> buffer(buffer_size);
343  std::string result;
344 #ifdef _WIN32
345  std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(command, "r"), _pclose);
346 #elif __linux__
347  std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command, "r"), pclose);
348 #else
349 #error "platform not supported"
350 #endif
351  if (!pipe)
352  {
353  throw std::runtime_error("popen() failed!");
354  }
355  while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr)
356  {
357  result += buffer.data();
358  }
359  return result;
360  }
361 
363  inline int RunExe(const std::string &exe_path, const std::string &cmd_arguments = "")
364  {
365 #ifdef _WIN32
366  // additional information
367  STARTUPINFO si;
368  PROCESS_INFORMATION pi;
369 
370  // set the size of the structures
371  ZeroMemory(&si, sizeof(si));
372  si.cb = sizeof(si);
373  ZeroMemory(&pi, sizeof(pi));
374 
375  const std::wstring exe_pathW = std_ext::ToWString(exe_path);
376  const std::wstring cmd_argumentsW = std_ext::ToWString(cmd_arguments);
377 
378  // start the program up
379  CreateProcess(exe_pathW.c_str(), // the path
380  const_cast<wchar_t *>((exe_pathW + L" " + cmd_argumentsW).c_str()), // Command line
381  NULL, // Process handle not inheritable
382  NULL, // Thread handle not inheritable
383  FALSE, // Set handle inheritance to FALSE
384  0, // No creation flags
385  NULL, // Use parent's environment block
386  NULL, // Use parent's starting directory
387  &si, // Pointer to STARTUPINFO structure
388  &pi // Pointer to PROCESS_INFORMATION structure (removed extra parentheses)
389  );
390 
391  WaitForSingleObject(pi.hProcess, INFINITE);
392 
393  // Get return value
394  DWORD exitCode;
395  const bool is_exit_code = GetExitCodeProcess(pi.hProcess, &exitCode);
396  const int commandReturnValue = is_exit_code ? static_cast<int>(exitCode) : -1;
397 
398  // Close process and thread handles.
399  CloseHandle(pi.hProcess);
400  CloseHandle(pi.hThread);
401 
402  return commandReturnValue;
403 
404 #elif __linux__
405  const int commandReturnValue = (exe_path[0] == '/')
406  ? system((exe_path + " " + cmd_arguments).c_str())
407  : system(("./" + exe_path + " " + cmd_arguments).c_str());
408 
409  if (commandReturnValue < 0)
410  {
411  std::cout << "Command: " << exe_path << " " << cmd_arguments << " failed." << std::endl;
412  }
413  return commandReturnValue;
414 #else
415 #error "platform not supported"
416 #endif
417  }
418 
424  inline std::string StripExtension(const std::string &file_name_with_extension)
425  {
426  const auto endpos = file_name_with_extension.find_first_of(".", 0);
427  return file_name_with_extension.substr(0, endpos);
428  }
429 
439  inline bool FileExistsInDirectory(const std::string &dir_path, const std::string &filename, bool strip_extension = false)
440  {
441  return std_ext::AnyOf(ListDirectoryFileNames(dir_path), [&](const auto & file)
442  {
443  const auto file_in_directory = StripExtension(file);
444  if(strip_extension)
445  {
446  return StripExtension(filename) == file_in_directory;
447  }
448  return filename == file_in_directory;
449  });
450  }
451 }
452 
453 #endif /* !UTILS_FILESYSTEM_H */
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