File.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-08-15
  6. * Changed: 2023-05-16
  7. *
  8. * */
  9. #include <algorithm>
  10. #include <cstdio>
  11. #ifdef _WIN32
  12. #include <direct.h>
  13. #endif
  14. #include <fstream>
  15. #include <list>
  16. #include <ls-std/core/exception/FileOperationException.hpp>
  17. #include <ls-std/io/File.hpp>
  18. #include <ls-std/io/FilePathSeparator.hpp>
  19. #include <ls-std/io/FilePathSeparatorMatch.hpp>
  20. #include <numeric>
  21. #include <sstream>
  22. #include <sys/stat.h>
  23. #ifdef _WIN32
  24. #include <tchar.h>
  25. #endif
  26. #if defined(unix) || defined(__APPLE__)
  27. #include <unistd.h>
  28. #endif
  29. #include <vector>
  30. using ls::std::core::Class;
  31. using ls::std::core::FileOperationException;
  32. using ls::std::io::File;
  33. using ls::std::io::FilePathSeparator;
  34. using ls::std::io::FilePathSeparatorMatch;
  35. using std::accumulate;
  36. using std::find_if;
  37. using std::getline;
  38. using std::ifstream;
  39. using std::ios;
  40. using std::list;
  41. using std::move;
  42. using std::ofstream;
  43. using std::remove;
  44. using std::remove_if;
  45. using std::rename;
  46. using std::replace;
  47. using std::streampos;
  48. using std::string;
  49. using std::stringstream;
  50. using std::vector;
  51. File::File(string _absoluteFilePath) : Class("File"), absoluteFilePath(File::_normalizePath(::move(_absoluteFilePath)))
  52. {}
  53. File::~File() noexcept = default;
  54. bool File::operator==(const File &_file) const
  55. {
  56. return File::_equals(*this, _file);
  57. }
  58. bool File::operator!=(const File &_file) const
  59. {
  60. return !File::_equals(*this, _file);
  61. }
  62. bool File::canExecute() const
  63. {
  64. return File::_isExecutable(this->absoluteFilePath);
  65. }
  66. bool File::canRead() const
  67. {
  68. bool readable{};
  69. #if defined(unix) || defined(__APPLE__)
  70. readable = File::_isReadableUnix(this->absoluteFilePath);
  71. #endif
  72. #ifdef _WIN32
  73. readable = File::_isReadableWindows(this->absoluteFilePath);
  74. #endif
  75. return readable;
  76. }
  77. bool File::canWrite() const
  78. {
  79. return File::_isWritable(this->absoluteFilePath);
  80. }
  81. void File::createNewFile() const
  82. {
  83. if (!File::_exists(this->absoluteFilePath))
  84. {
  85. ofstream file{this->absoluteFilePath};
  86. file.close();
  87. }
  88. else
  89. {
  90. throw FileOperationException{R"lit(file ")lit" + this->absoluteFilePath + R"lit(" could not be created!)lit"};
  91. }
  92. }
  93. bool File::exists() const
  94. {
  95. return File::_exists(this->absoluteFilePath);
  96. }
  97. string File::getAbsoluteFilePath() const
  98. {
  99. return this->absoluteFilePath;
  100. }
  101. string File::getName() const
  102. {
  103. string copy = this->absoluteFilePath;
  104. // if it's a directory, remove separator from end, if it does exist
  105. if (File::_isDirectory(this->absoluteFilePath))
  106. {
  107. copy.erase(remove_if(copy.end() - 1, copy.end(), FilePathSeparatorMatch()), copy.end());
  108. }
  109. // now get the file / directory name
  110. auto base = find_if(copy.rbegin(), copy.rend(), FilePathSeparatorMatch()).base();
  111. return string{base, copy.end()};
  112. }
  113. string File::getParent() const
  114. {
  115. return File::_getParent(this->absoluteFilePath);
  116. }
  117. string File::getWorkingDirectory()
  118. {
  119. string workingDirectory{};
  120. #if defined(unix) || defined(__APPLE__)
  121. workingDirectory = File::_getWorkingDirectoryUnix();
  122. #endif
  123. #ifdef _WIN32
  124. workingDirectory = File::_getWorkingDirectoryWindows();
  125. #endif
  126. return workingDirectory;
  127. }
  128. long File::getSize() const
  129. {
  130. streampos fileSize{};
  131. if (File::_exists(this->absoluteFilePath))
  132. {
  133. ifstream fileHandler{this->absoluteFilePath, ios::in};
  134. fileSize = fileHandler.tellg();
  135. fileHandler.seekg(0, ios::end);
  136. fileSize = fileHandler.tellg() - fileSize;
  137. fileHandler.close();
  138. }
  139. return (long) fileSize;
  140. }
  141. bool File::isDirectory() const
  142. {
  143. return File::_isDirectory(this->absoluteFilePath);
  144. }
  145. bool File::isFile() const
  146. {
  147. return File::_isFile(this->absoluteFilePath);
  148. }
  149. time_t File::lastModified() const
  150. {
  151. return File::_lastModified(this->absoluteFilePath);
  152. }
  153. ::list<string> File::list() const
  154. {
  155. ::list<string> fileList{};
  156. if (File::_isDirectory(this->absoluteFilePath))
  157. {
  158. fileList = File::_list(this->absoluteFilePath);
  159. }
  160. return fileList;
  161. }
  162. ::list<string> File::listFiles() const
  163. {
  164. ::list<string> fileList{};
  165. if (File::_isDirectory(this->absoluteFilePath))
  166. {
  167. fileList = File::_listFiles(this->absoluteFilePath);
  168. }
  169. return fileList;
  170. }
  171. void File::makeDirectory() const
  172. {
  173. if (!File::_makeDirectory(this->absoluteFilePath))
  174. {
  175. throw FileOperationException{R"lit(directory ")lit" + this->absoluteFilePath + R"lit(" could not be created!)lit"};
  176. }
  177. }
  178. void File::makeDirectories() const
  179. {
  180. vector<string> subDirectories = File::_splitIntoSubDirectoryNames(this->absoluteFilePath);
  181. const char separator = FilePathSeparator::get();
  182. string currentHierarchy{};
  183. for (const auto &subDirectory : subDirectories)
  184. {
  185. currentHierarchy += subDirectory;
  186. if (!File::_exists(currentHierarchy + separator) && !currentHierarchy.empty() && !File::_makeDirectory(currentHierarchy))
  187. {
  188. throw FileOperationException{"operation: create directory"};
  189. }
  190. currentHierarchy += separator;
  191. }
  192. }
  193. void File::remove() const
  194. {
  195. if (File::_isFile(this->absoluteFilePath))
  196. {
  197. ::remove(this->absoluteFilePath.c_str());
  198. }
  199. if (File::_isDirectory(this->absoluteFilePath))
  200. {
  201. File::_remove(this->absoluteFilePath);
  202. }
  203. }
  204. bool File::renameTo(const string &_newName)
  205. {
  206. bool renamed = File::_renameTo(this->absoluteFilePath, _newName);
  207. if (renamed)
  208. {
  209. this->absoluteFilePath = _newName;
  210. }
  211. return renamed;
  212. }
  213. void File::reset(const string &_newPath)
  214. {
  215. this->absoluteFilePath = File::_normalizePath(_newPath);
  216. }
  217. #ifdef _WIN32
  218. void File::_addToFileListWindows(const string &_path, bool _withDirectories, WIN32_FIND_DATA _data, ::list<string> &_list)
  219. {
  220. const char separator = FilePathSeparator::get();
  221. string absolutePath = _path + separator + _data.cFileName;
  222. if (_withDirectories)
  223. {
  224. _list.emplace_back(absolutePath);
  225. }
  226. else
  227. {
  228. if (File::_isFile(absolutePath))
  229. {
  230. _list.emplace_back(absolutePath);
  231. }
  232. }
  233. }
  234. #endif
  235. #if defined(unix) || defined(__APPLE__)
  236. void File::_addToFileListUnix(const string &_path, bool _withDirectories, const dirent *directoryEntity, ::list<string> &_list)
  237. {
  238. const char separator = FilePathSeparator::get();
  239. string absolutePath = _path + separator + directoryEntity->d_name;
  240. if (_withDirectories)
  241. {
  242. _list.emplace_back(absolutePath);
  243. }
  244. else
  245. {
  246. if (File::_isFile(absolutePath))
  247. {
  248. _list.emplace_back(absolutePath);
  249. }
  250. }
  251. }
  252. #endif
  253. bool File::_equals(const File &_file, const File &_foreignFile)
  254. {
  255. bool isEqual = _file.getAbsoluteFilePath() == _foreignFile.getAbsoluteFilePath();
  256. if (_file.exists() && _foreignFile.exists())
  257. {
  258. isEqual = isEqual && _file.canRead() == _foreignFile.canRead();
  259. isEqual = isEqual && _file.canWrite() == _foreignFile.canWrite();
  260. isEqual = isEqual && _file.canExecute() == _foreignFile.canExecute();
  261. }
  262. return isEqual;
  263. }
  264. bool File::_exists(const string &_path)
  265. {
  266. struct stat _stat
  267. {
  268. };
  269. return (stat(_path.c_str(), &_stat) == 0);
  270. }
  271. string File::_getParent(const string &_path)
  272. {
  273. vector<string> subDirectoryNames = File::_splitIntoSubDirectoryNames(_path);
  274. const char separator = FilePathSeparator::get();
  275. subDirectoryNames.pop_back();
  276. return accumulate(subDirectoryNames.begin(), subDirectoryNames.end(), string{}, [separator](string parent, const string &subDirectoryName) { return ::move(parent) + subDirectoryName + separator; });
  277. }
  278. #if defined(unix) || defined(__APPLE__)
  279. string File::_getWorkingDirectoryUnix()
  280. {
  281. string workingDirectory{};
  282. if (string buffer(PATH_MAX, 'x'); getcwd(buffer.data(), buffer.size()) == nullptr)
  283. {
  284. throw FileOperationException{"operation: get working directory"};
  285. }
  286. else
  287. {
  288. workingDirectory = string(buffer);
  289. }
  290. return workingDirectory;
  291. }
  292. #endif
  293. #ifdef _WIN32
  294. string File::_getWorkingDirectoryWindows()
  295. {
  296. string workingDirectory{};
  297. TCHAR buffer[MAX_PATH];
  298. if (!GetCurrentDirectory(MAX_PATH, buffer))
  299. {
  300. throw FileOperationException{"operation: get working directory"};
  301. }
  302. else
  303. {
  304. workingDirectory = string(buffer);
  305. }
  306. return workingDirectory;
  307. }
  308. #endif
  309. bool File::_isDirectory(const string &_path)
  310. {
  311. bool match{};
  312. if (struct stat _stat{}; stat(_path.c_str(), &_stat) == 0)
  313. {
  314. match = _stat.st_mode & (unsigned short) S_IFDIR;
  315. }
  316. return match;
  317. }
  318. bool File::_isExecutable(const string &_path)
  319. {
  320. bool executable{};
  321. if (File::_exists(_path))
  322. {
  323. struct stat _stat
  324. {
  325. };
  326. if (stat(_path.c_str(), &_stat) == 0)
  327. {
  328. executable = (_stat.st_mode & (unsigned short) S_IEXEC) != 0;
  329. }
  330. }
  331. return executable;
  332. }
  333. bool File::_isFile(const string &_path)
  334. {
  335. bool match{};
  336. if (struct stat _stat{}; stat(_path.c_str(), &_stat) == 0)
  337. {
  338. match = _stat.st_mode & (unsigned) S_IFREG;
  339. }
  340. return match;
  341. }
  342. #if defined(unix) || defined(__APPLE__)
  343. bool File::_isReadableUnix(const string &_path)
  344. {
  345. bool readable{};
  346. if (File::_exists(_path))
  347. {
  348. struct stat _stat
  349. {
  350. };
  351. if (stat(_path.c_str(), &_stat) == 0)
  352. {
  353. readable = (_stat.st_mode & (unsigned) S_IREAD) != 0;
  354. }
  355. }
  356. else
  357. {
  358. throw FileOperationException{"operation: fetch permissions"};
  359. }
  360. return readable;
  361. }
  362. #endif
  363. #ifdef _WIN32
  364. bool File::_isReadableWindows(const string &_path)
  365. {
  366. bool readable;
  367. WIN32_FIND_DATA data{};
  368. HANDLE handleFind = FindFirstFile(_path.c_str(), &data);
  369. if (handleFind != INVALID_HANDLE_VALUE)
  370. {
  371. readable = GetFileAttributes(data.cFileName) & (unsigned) FILE_ATTRIBUTE_READONLY;
  372. }
  373. else
  374. {
  375. throw FileOperationException{"operation: fetch permissions"};
  376. }
  377. return readable;
  378. }
  379. #endif
  380. bool File::_isWritable(const string &_path)
  381. {
  382. bool writable{};
  383. if (File::_exists(_path))
  384. {
  385. struct stat _stat
  386. {
  387. };
  388. if (stat(_path.c_str(), &_stat) == 0)
  389. {
  390. writable = (_stat.st_mode & (unsigned) S_IWRITE) != 0;
  391. }
  392. }
  393. return writable;
  394. }
  395. time_t File::_lastModified(const string &_path)
  396. {
  397. time_t lastModifiedTimeStamp{};
  398. if (struct stat _stat{}; stat(_path.c_str(), &_stat) == 0)
  399. {
  400. lastModifiedTimeStamp = _stat.st_mtime;
  401. }
  402. return lastModifiedTimeStamp;
  403. }
  404. ::list<string> File::_list(const string &_path)
  405. {
  406. ::list<string> filesInDirectory{};
  407. #if defined(unix) || defined(__APPLE__)
  408. filesInDirectory = File::_listUnix(_path, true);
  409. #endif
  410. #ifdef _WIN32
  411. filesInDirectory = File::_listWindows(_path, true);
  412. #endif
  413. return filesInDirectory;
  414. }
  415. ::list<string> File::_listFiles(const string &_path)
  416. {
  417. ::list<string> filesInDirectory{};
  418. #if defined(unix) || defined(__APPLE__)
  419. filesInDirectory = File::_listUnix(_path, false);
  420. #endif
  421. #ifdef _WIN32
  422. filesInDirectory = File::_listWindows(_path, false);
  423. #endif
  424. return filesInDirectory;
  425. }
  426. #if defined(unix) || defined(__APPLE__)
  427. ::list<string> File::_listUnix(const string &_path, bool withDirectories)
  428. {
  429. ::list<string> filesInDirectory{};
  430. DIR *directory = opendir(_path.c_str());
  431. const struct dirent *directoryEntity;
  432. string absolutePath{};
  433. while ((directoryEntity = readdir(directory)) != nullptr)
  434. {
  435. File::_addToFileListUnix(_path, withDirectories, directoryEntity, filesInDirectory);
  436. }
  437. closedir(directory);
  438. return filesInDirectory;
  439. }
  440. #endif
  441. #ifdef _WIN32
  442. ::list<string> File::_listWindows(const string &_path, bool withDirectories)
  443. {
  444. ::list<string> filesInDirectory{};
  445. WIN32_FIND_DATA data{};
  446. HANDLE hFind;
  447. string pattern{_path + FilePathSeparator::get() + "*"};
  448. if ((hFind = FindFirstFile(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE)
  449. {
  450. do
  451. {
  452. File::_addToFileListWindows(_path, withDirectories, data, filesInDirectory);
  453. } while (FindNextFile(hFind, &data) != 0);
  454. FindClose(hFind);
  455. }
  456. return filesInDirectory;
  457. }
  458. #endif
  459. bool File::_makeDirectory(const string &_path)
  460. {
  461. int result{};
  462. #ifdef _WIN32
  463. result = _mkdir(_path.c_str());
  464. #endif
  465. #if defined(unix) || defined(__APPLE__)
  466. result = mkdir(_path.c_str(), 0777);
  467. #endif
  468. return result == 0;
  469. }
  470. string File::_normalizePath(string _path)
  471. {
  472. _path = File::_replaceWrongSeparator(_path);
  473. _path = File::_reduceSeparators(_path);
  474. return _path;
  475. }
  476. string File::_reduceSeparators(const string &_path)
  477. {
  478. static const char separator = {FilePathSeparator::get()};
  479. string normalizedPath{};
  480. int index{};
  481. while (index < _path.size())
  482. {
  483. if (_path[index] == separator)
  484. {
  485. normalizedPath += _path[index];
  486. do
  487. {
  488. index++;
  489. } while (_path[index] == separator);
  490. }
  491. else
  492. {
  493. normalizedPath += _path[index];
  494. index++;
  495. }
  496. }
  497. return normalizedPath;
  498. }
  499. void File::_remove(const string &_path)
  500. {
  501. #if defined(unix) || defined(__APPLE__)
  502. File::_removeUnix(_path);
  503. #endif
  504. #ifdef _WIN32
  505. File::_removeWindows(_path);
  506. #endif
  507. }
  508. #if defined(unix) || defined(__APPLE__)
  509. void File::_removeUnix(const string &_path)
  510. {
  511. rmdir(_path.c_str());
  512. }
  513. #endif
  514. #ifdef _WIN32
  515. void File::_removeWindows(const string &_path)
  516. {
  517. _rmdir(_path.c_str());
  518. }
  519. #endif
  520. bool File::_renameTo(const string &_oldName, const string &_newName)
  521. {
  522. return rename(_oldName.c_str(), _newName.c_str()) == 0;
  523. }
  524. string File::_replaceWrongSeparator(string _path)
  525. {
  526. static const char unixSeparator = FilePathSeparator::getUnixFilePathSeparator();
  527. static const char windowsSeparator = FilePathSeparator::getWindowsFilePathSeparator();
  528. #if defined(unix) || defined(__APPLE__)
  529. replace(_path.begin(), _path.end(), windowsSeparator, unixSeparator);
  530. #endif
  531. #ifdef _WIN32
  532. replace(_path.begin(), _path.end(), unixSeparator, windowsSeparator);
  533. #endif
  534. return _path;
  535. }
  536. vector<string> File::_splitIntoSubDirectoryNames(const string &_path)
  537. {
  538. vector<string> subDirectoryNames{};
  539. stringstream _stream{_path};
  540. string subDirectoryName{};
  541. const char separator = FilePathSeparator::get();
  542. while (getline(_stream, subDirectoryName, separator))
  543. {
  544. subDirectoryNames.push_back(subDirectoryName);
  545. }
  546. return subDirectoryNames;
  547. }