File.cpp 13 KB

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