File.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-08-15
  6. * Changed: 2023-04-13
  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==(File &_file)
  55. {
  56. return File::_equals(*this, _file);
  57. }
  58. bool File::operator!=(File &_file)
  59. {
  60. return !File::_equals(*this, _file);
  61. }
  62. bool File::canExecute()
  63. {
  64. return File::_isExecutable(this->absoluteFilePath);
  65. }
  66. bool File::canRead()
  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()
  78. {
  79. return File::_isWritable(this->absoluteFilePath);
  80. }
  81. void File::createNewFile()
  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()
  94. {
  95. return File::_exists(this->absoluteFilePath);
  96. }
  97. string File::getAbsoluteFilePath()
  98. {
  99. return this->absoluteFilePath;
  100. }
  101. string File::getName()
  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()
  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()
  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()
  142. {
  143. return File::_isDirectory(this->absoluteFilePath);
  144. }
  145. bool File::isFile()
  146. {
  147. return File::_isFile(this->absoluteFilePath);
  148. }
  149. time_t File::lastModified()
  150. {
  151. return File::_lastModified(this->absoluteFilePath);
  152. }
  153. ::list<string> File::list()
  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()
  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()
  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()
  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())
  187. {
  188. if (!File::_makeDirectory(currentHierarchy))
  189. {
  190. throw FileOperationException{"operation: create directory"};
  191. }
  192. }
  193. currentHierarchy += separator;
  194. }
  195. }
  196. void File::remove()
  197. {
  198. if (File::_isFile(this->absoluteFilePath))
  199. {
  200. ::remove(this->absoluteFilePath.c_str());
  201. }
  202. if (File::_isDirectory(this->absoluteFilePath))
  203. {
  204. File::_remove(this->absoluteFilePath);
  205. }
  206. }
  207. bool File::renameTo(const string &_newName)
  208. {
  209. bool renamed = File::_renameTo(this->absoluteFilePath, _newName);
  210. if (renamed)
  211. {
  212. this->absoluteFilePath = _newName;
  213. }
  214. return renamed;
  215. }
  216. void File::reset(const string &_newPath)
  217. {
  218. this->absoluteFilePath = File::_normalizePath(_newPath);
  219. }
  220. #ifdef _WIN32
  221. void File::_addToFileListWindows(const string &_path, bool _withDirectories, WIN32_FIND_DATA _data, ::list<string> &_list)
  222. {
  223. const char separator = FilePathSeparator::get();
  224. string absolutePath = _path + separator + _data.cFileName;
  225. if (_withDirectories)
  226. {
  227. _list.emplace_back(absolutePath);
  228. }
  229. else
  230. {
  231. if (File::_isFile(absolutePath))
  232. {
  233. _list.emplace_back(absolutePath);
  234. }
  235. }
  236. }
  237. #endif
  238. #if defined(unix) || defined(__APPLE__)
  239. void File::_addToFileListUnix(const string &_path, bool _withDirectories, dirent *directoryEntity, ::list<string> &_list)
  240. {
  241. const char separator = FilePathSeparator::get();
  242. string absolutePath = _path + separator + directoryEntity->d_name;
  243. if (_withDirectories)
  244. {
  245. _list.emplace_back(absolutePath);
  246. }
  247. else
  248. {
  249. if (File::_isFile(absolutePath))
  250. {
  251. _list.emplace_back(absolutePath);
  252. }
  253. }
  254. }
  255. #endif
  256. bool File::_equals(File &_file, File &_foreignFile)
  257. {
  258. bool isEqual = _file.getAbsoluteFilePath() == _foreignFile.getAbsoluteFilePath();
  259. if (_file.exists() && _foreignFile.exists())
  260. {
  261. isEqual = isEqual && _file.canRead() == _foreignFile.canRead();
  262. isEqual = isEqual && _file.canWrite() == _foreignFile.canWrite();
  263. isEqual = isEqual && _file.canExecute() == _foreignFile.canExecute();
  264. }
  265. return isEqual;
  266. }
  267. bool File::_exists(const string &_path)
  268. {
  269. struct stat _stat
  270. {
  271. };
  272. return (stat(_path.c_str(), &_stat) == 0);
  273. }
  274. string File::_getParent(const string &_path)
  275. {
  276. vector<string> subDirectoryNames = File::_splitIntoSubDirectoryNames(_path);
  277. const char separator = FilePathSeparator::get();
  278. subDirectoryNames.pop_back();
  279. return accumulate(subDirectoryNames.begin(), subDirectoryNames.end(), string{}, [separator](string parent, const string &subDirectoryName) { return ::move(parent) + subDirectoryName + separator; });
  280. }
  281. #if defined(unix) || defined(__APPLE__)
  282. string File::_getWorkingDirectoryUnix()
  283. {
  284. string workingDirectory{};
  285. char buffer[PATH_MAX];
  286. if (getcwd(buffer, sizeof(buffer)) == nullptr)
  287. {
  288. throw FileOperationException{"operation: get working directory"};
  289. }
  290. else
  291. {
  292. workingDirectory = string(buffer);
  293. }
  294. return workingDirectory;
  295. }
  296. #endif
  297. #ifdef _WIN32
  298. string File::_getWorkingDirectoryWindows()
  299. {
  300. string workingDirectory{};
  301. TCHAR buffer[MAX_PATH];
  302. if (!GetCurrentDirectory(MAX_PATH, buffer))
  303. {
  304. throw FileOperationException{"operation: get working directory"};
  305. }
  306. else
  307. {
  308. workingDirectory = string(buffer);
  309. }
  310. return workingDirectory;
  311. }
  312. #endif
  313. bool File::_isDirectory(const string &_path)
  314. {
  315. bool match{};
  316. struct stat _stat
  317. {
  318. };
  319. if (stat(_path.c_str(), &_stat) == 0)
  320. {
  321. match = _stat.st_mode & (unsigned short) S_IFDIR;
  322. }
  323. return match;
  324. }
  325. bool File::_isExecutable(const string &_path)
  326. {
  327. bool executable{};
  328. if (File::_exists(_path))
  329. {
  330. struct stat _stat
  331. {
  332. };
  333. if (stat(_path.c_str(), &_stat) == 0)
  334. {
  335. executable = (_stat.st_mode & (unsigned short) S_IEXEC) != 0;
  336. }
  337. }
  338. return executable;
  339. }
  340. bool File::_isFile(const string &_path)
  341. {
  342. bool match{};
  343. struct stat _stat
  344. {
  345. };
  346. if (stat(_path.c_str(), &_stat) == 0)
  347. {
  348. match = _stat.st_mode & (unsigned) S_IFREG;
  349. }
  350. return match;
  351. }
  352. #if defined(unix) || defined(__APPLE__)
  353. bool File::_isReadableUnix(const string &_path)
  354. {
  355. bool readable{};
  356. if (File::_exists(_path))
  357. {
  358. struct stat _stat
  359. {
  360. };
  361. if (stat(_path.c_str(), &_stat) == 0)
  362. {
  363. readable = (_stat.st_mode & (unsigned) S_IREAD) != 0;
  364. }
  365. }
  366. else
  367. {
  368. throw FileOperationException{"operation: fetch permissions"};
  369. }
  370. return readable;
  371. }
  372. #endif
  373. #ifdef _WIN32
  374. bool File::_isReadableWindows(const string &_path)
  375. {
  376. bool readable;
  377. WIN32_FIND_DATA data{};
  378. HANDLE handleFind = FindFirstFile(_path.c_str(), &data);
  379. if (handleFind != INVALID_HANDLE_VALUE)
  380. {
  381. readable = GetFileAttributes(data.cFileName) & (unsigned) FILE_ATTRIBUTE_READONLY;
  382. }
  383. else
  384. {
  385. throw FileOperationException{"operation: fetch permissions"};
  386. }
  387. return readable;
  388. }
  389. #endif
  390. bool File::_isWritable(const string &_path)
  391. {
  392. bool writable{};
  393. if (File::_exists(_path))
  394. {
  395. struct stat _stat
  396. {
  397. };
  398. if (stat(_path.c_str(), &_stat) == 0)
  399. {
  400. writable = (_stat.st_mode & (unsigned) S_IWRITE) != 0;
  401. }
  402. }
  403. return writable;
  404. }
  405. time_t File::_lastModified(const string &_path)
  406. {
  407. time_t lastModifiedTimeStamp{};
  408. struct stat _stat
  409. {
  410. };
  411. if (stat(_path.c_str(), &_stat) == 0)
  412. {
  413. lastModifiedTimeStamp = _stat.st_mtime;
  414. }
  415. return lastModifiedTimeStamp;
  416. }
  417. ::list<string> File::_list(const string &_path)
  418. {
  419. ::list<string> filesInDirectory{};
  420. #if defined(unix) || defined(__APPLE__)
  421. filesInDirectory = File::_listUnix(_path, true);
  422. #endif
  423. #ifdef _WIN32
  424. filesInDirectory = File::_listWindows(_path, true);
  425. #endif
  426. return filesInDirectory;
  427. }
  428. ::list<string> File::_listFiles(const string &_path)
  429. {
  430. ::list<string> filesInDirectory{};
  431. #if defined(unix) || defined(__APPLE__)
  432. filesInDirectory = File::_listUnix(_path, false);
  433. #endif
  434. #ifdef _WIN32
  435. filesInDirectory = File::_listWindows(_path, false);
  436. #endif
  437. return filesInDirectory;
  438. }
  439. #if defined(unix) || defined(__APPLE__)
  440. ::list<string> File::_listUnix(const string &_path, bool withDirectories)
  441. {
  442. ::list<string> filesInDirectory{};
  443. DIR *directory = opendir(_path.c_str());
  444. struct dirent *directoryEntity;
  445. string absolutePath{};
  446. while ((directoryEntity = readdir(directory)) != nullptr)
  447. {
  448. File::_addToFileListUnix(_path, withDirectories, directoryEntity, filesInDirectory);
  449. }
  450. closedir(directory);
  451. return filesInDirectory;
  452. }
  453. #endif
  454. #ifdef _WIN32
  455. ::list<string> File::_listWindows(const string &_path, bool withDirectories)
  456. {
  457. ::list<string> filesInDirectory{};
  458. WIN32_FIND_DATA data{};
  459. HANDLE hFind;
  460. string pattern{_path + FilePathSeparator::get() + "*"};
  461. if ((hFind = FindFirstFile(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE)
  462. {
  463. do
  464. {
  465. File::_addToFileListWindows(_path, withDirectories, data, filesInDirectory);
  466. } while (FindNextFile(hFind, &data) != 0);
  467. FindClose(hFind);
  468. }
  469. return filesInDirectory;
  470. }
  471. #endif
  472. bool File::_makeDirectory(const string &_path)
  473. {
  474. int result{};
  475. #ifdef _WIN32
  476. result = _mkdir(_path.c_str());
  477. #endif
  478. #if defined(unix) || defined(__APPLE__)
  479. result = mkdir(_path.c_str(), 0777);
  480. #endif
  481. return result == 0;
  482. }
  483. string File::_normalizePath(string _path)
  484. {
  485. _path = File::_replaceWrongSeparator(_path);
  486. _path = File::_reduceSeparators(_path);
  487. return _path;
  488. }
  489. string File::_reduceSeparators(const string &_path)
  490. {
  491. static const char separator = {FilePathSeparator::get()};
  492. string normalizedPath{};
  493. int index{};
  494. while (index < _path.size())
  495. {
  496. if (_path[index] == separator)
  497. {
  498. normalizedPath += _path[index];
  499. do
  500. {
  501. index++;
  502. } while (_path[index] == separator);
  503. }
  504. else
  505. {
  506. normalizedPath += _path[index];
  507. index++;
  508. }
  509. }
  510. return normalizedPath;
  511. }
  512. void File::_remove(const string &_path)
  513. {
  514. #if defined(unix) || defined(__APPLE__)
  515. File::_removeUnix(_path);
  516. #endif
  517. #ifdef _WIN32
  518. File::_removeWindows(_path);
  519. #endif
  520. }
  521. #if defined(unix) || defined(__APPLE__)
  522. void File::_removeUnix(const string &_path)
  523. {
  524. rmdir(_path.c_str());
  525. }
  526. #endif
  527. #ifdef _WIN32
  528. void File::_removeWindows(const string &_path)
  529. {
  530. _rmdir(_path.c_str());
  531. }
  532. #endif
  533. bool File::_renameTo(const string &_oldName, const string &_newName)
  534. {
  535. return rename(_oldName.c_str(), _newName.c_str()) == 0;
  536. }
  537. string File::_replaceWrongSeparator(string _path)
  538. {
  539. static const char unixSeparator = FilePathSeparator::getUnixFilePathSeparator();
  540. static const char windowsSeparator = FilePathSeparator::getWindowsFilePathSeparator();
  541. #if defined(unix) || defined(__APPLE__)
  542. replace(_path.begin(), _path.end(), windowsSeparator, unixSeparator);
  543. #endif
  544. #ifdef _WIN32
  545. replace(_path.begin(), _path.end(), unixSeparator, windowsSeparator);
  546. #endif
  547. return _path;
  548. }
  549. vector<string> File::_splitIntoSubDirectoryNames(const string &_path)
  550. {
  551. vector<string> subDirectoryNames{};
  552. stringstream _stream{_path};
  553. string subDirectoryName{};
  554. const char separator = FilePathSeparator::get();
  555. while (getline(_stream, subDirectoryName, separator))
  556. {
  557. subDirectoryNames.push_back(subDirectoryName);
  558. }
  559. return subDirectoryNames;
  560. }