File.cpp 14 KB

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