BsWin32FileSystem.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsFileSystem.h"
  4. #include "BsException.h"
  5. #include "BsDataStream.h"
  6. #include "BsDebug.h"
  7. #include <windows.h>
  8. namespace BansheeEngine
  9. {
  10. void win32_handleError(DWORD error, const WString& path)
  11. {
  12. switch (error)
  13. {
  14. case ERROR_FILE_NOT_FOUND:
  15. LOGERR("File at path: \"" + toString(path) + "\" not found.");
  16. break;
  17. case ERROR_PATH_NOT_FOUND:
  18. case ERROR_BAD_NETPATH:
  19. case ERROR_CANT_RESOLVE_FILENAME:
  20. case ERROR_INVALID_DRIVE:
  21. LOGERR("Path \"" + toString(path) + "\" not found.");
  22. break;
  23. case ERROR_ACCESS_DENIED:
  24. LOGERR("Access to path \"" + toString(path) + "\" denied.");
  25. break;
  26. case ERROR_ALREADY_EXISTS:
  27. case ERROR_FILE_EXISTS:
  28. LOGERR("File/folder at path \"" + toString(path) + "\" already exists.");
  29. break;
  30. case ERROR_INVALID_NAME:
  31. case ERROR_DIRECTORY:
  32. case ERROR_FILENAME_EXCED_RANGE:
  33. case ERROR_BAD_PATHNAME:
  34. LOGERR("Invalid path string: \"" + toString(path) + "\".");
  35. break;
  36. case ERROR_FILE_READ_ONLY:
  37. LOGERR("File at path \"" + toString(path) + "\" is read only.");
  38. break;
  39. case ERROR_CANNOT_MAKE:
  40. LOGERR("Cannot create file/folder at path: \"" + toString(path) + "\".");
  41. break;
  42. case ERROR_DIR_NOT_EMPTY:
  43. LOGERR("Directory at path \"" + toString(path) + "\" not empty.");
  44. break;
  45. case ERROR_WRITE_FAULT:
  46. LOGERR("Error while writing a file at path \"" + toString(path) + "\".");
  47. break;
  48. case ERROR_READ_FAULT:
  49. LOGERR("Error while reading a file at path \"" + toString(path) + "\".");
  50. break;
  51. case ERROR_SHARING_VIOLATION:
  52. LOGERR("Sharing violation at path \"" + toString(path) + "\".");
  53. break;
  54. case ERROR_LOCK_VIOLATION:
  55. LOGERR("Lock violation at path \"" + toString(path) + "\".");
  56. break;
  57. case ERROR_HANDLE_EOF:
  58. LOGERR("End of file reached for file at path \"" + toString(path) + "\".");
  59. break;
  60. case ERROR_HANDLE_DISK_FULL:
  61. case ERROR_DISK_FULL:
  62. LOGERR("Disk full.");
  63. break;
  64. case ERROR_NEGATIVE_SEEK:
  65. LOGERR("Negative seek.");
  66. break;
  67. default:
  68. LOGERR("Undefined file system exception: " + toString((UINT32)error));
  69. break;
  70. }
  71. }
  72. WString win32_getCurrentDirectory()
  73. {
  74. DWORD len = GetCurrentDirectoryW(0, NULL);
  75. if (len > 0)
  76. {
  77. wchar_t* buffer = (wchar_t*)bs_alloc(len * sizeof(wchar_t));
  78. DWORD n = GetCurrentDirectoryW(len, buffer);
  79. if (n > 0 && n <= len)
  80. {
  81. WString result(buffer);
  82. if (result[result.size() - 1] != '\\')
  83. result.append(L"\\");
  84. bs_free(buffer);
  85. return result;
  86. }
  87. bs_free(buffer);
  88. }
  89. return StringUtil::WBLANK;
  90. }
  91. WString win32_getTempDirectory()
  92. {
  93. DWORD len = GetTempPathW(0, NULL);
  94. if (len > 0)
  95. {
  96. wchar_t* buffer = (wchar_t*)bs_alloc(len * sizeof(wchar_t));
  97. DWORD n = GetTempPathW(len, buffer);
  98. if (n > 0 && n <= len)
  99. {
  100. WString result(buffer);
  101. if (result[result.size() - 1] != '\\')
  102. result.append(L"\\");
  103. bs_free(buffer);
  104. return result;
  105. }
  106. bs_free(buffer);
  107. }
  108. return StringUtil::WBLANK;
  109. }
  110. bool win32_pathExists(const WString& path)
  111. {
  112. DWORD attr = GetFileAttributesW(path.c_str());
  113. if (attr == 0xFFFFFFFF)
  114. {
  115. switch (GetLastError())
  116. {
  117. case ERROR_FILE_NOT_FOUND:
  118. case ERROR_PATH_NOT_FOUND:
  119. case ERROR_NOT_READY:
  120. case ERROR_INVALID_DRIVE:
  121. return false;
  122. default:
  123. win32_handleError(GetLastError(), path);
  124. }
  125. }
  126. return true;
  127. }
  128. bool win32_isDirectory(const WString& path)
  129. {
  130. DWORD attr = GetFileAttributesW(path.c_str());
  131. if (attr == 0xFFFFFFFF)
  132. win32_handleError(GetLastError(), path);
  133. return (attr & FILE_ATTRIBUTE_DIRECTORY) != FALSE;
  134. }
  135. bool win32_isDevice(const WString& path)
  136. {
  137. WString ucPath = path;
  138. StringUtil::toUpperCase(ucPath);
  139. return
  140. ucPath.compare(0, 4, L"\\\\.\\") == 0 ||
  141. ucPath.compare(L"CON") == 0 ||
  142. ucPath.compare(L"PRN") == 0 ||
  143. ucPath.compare(L"AUX") == 0 ||
  144. ucPath.compare(L"NUL") == 0 ||
  145. ucPath.compare(L"LPT1") == 0 ||
  146. ucPath.compare(L"LPT2") == 0 ||
  147. ucPath.compare(L"LPT3") == 0 ||
  148. ucPath.compare(L"LPT4") == 0 ||
  149. ucPath.compare(L"LPT5") == 0 ||
  150. ucPath.compare(L"LPT6") == 0 ||
  151. ucPath.compare(L"LPT7") == 0 ||
  152. ucPath.compare(L"LPT8") == 0 ||
  153. ucPath.compare(L"LPT9") == 0 ||
  154. ucPath.compare(L"COM1") == 0 ||
  155. ucPath.compare(L"COM2") == 0 ||
  156. ucPath.compare(L"COM3") == 0 ||
  157. ucPath.compare(L"COM4") == 0 ||
  158. ucPath.compare(L"COM5") == 0 ||
  159. ucPath.compare(L"COM6") == 0 ||
  160. ucPath.compare(L"COM7") == 0 ||
  161. ucPath.compare(L"COM8") == 0 ||
  162. ucPath.compare(L"COM9") == 0;
  163. }
  164. bool win32_isFile(const WString& path)
  165. {
  166. return !win32_isDirectory(path) && !win32_isDevice(path);
  167. }
  168. bool win32_createFile(const WString& path)
  169. {
  170. HANDLE hFile = CreateFileW(path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0);
  171. if (hFile != INVALID_HANDLE_VALUE)
  172. {
  173. CloseHandle(hFile);
  174. return true;
  175. }
  176. else if (GetLastError() == ERROR_FILE_EXISTS)
  177. return false;
  178. else
  179. win32_handleError(GetLastError(), path);
  180. return false;
  181. }
  182. bool win32_createDirectory(const WString& path)
  183. {
  184. if (win32_pathExists(path) && win32_isDirectory(path))
  185. return false;
  186. if (CreateDirectoryW(path.c_str(), 0) == FALSE)
  187. win32_handleError(GetLastError(), path);
  188. return true;
  189. }
  190. void win32_remove(const WString& path)
  191. {
  192. if (win32_isDirectory(path))
  193. {
  194. if (RemoveDirectoryW(path.c_str()) == 0)
  195. win32_handleError(GetLastError(), path);
  196. }
  197. else
  198. {
  199. if (DeleteFileW(path.c_str()) == 0)
  200. win32_handleError(GetLastError(), path);
  201. }
  202. }
  203. void win32_copyFile(const WString& from, const WString& to)
  204. {
  205. if (CopyFileW(from.c_str(), to.c_str(), FALSE) == FALSE)
  206. win32_handleError(GetLastError(), from);
  207. }
  208. void win32_rename(const WString& oldPath, const WString& newPath)
  209. {
  210. if (MoveFileW(oldPath.c_str(), newPath.c_str()) == 0)
  211. win32_handleError(GetLastError(), oldPath);
  212. }
  213. UINT64 win32_getFileSize(const WString& path)
  214. {
  215. WIN32_FILE_ATTRIBUTE_DATA attrData;
  216. if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &attrData) == FALSE)
  217. win32_handleError(GetLastError(), path);
  218. LARGE_INTEGER li;
  219. li.LowPart = attrData.nFileSizeLow;
  220. li.HighPart = attrData.nFileSizeHigh;
  221. return (UINT64)li.QuadPart;
  222. }
  223. std::time_t win32_getLastModifiedTime(const WString& path)
  224. {
  225. WIN32_FILE_ATTRIBUTE_DATA fad;
  226. if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &fad) == 0)
  227. win32_handleError(GetLastError(), path);
  228. ULARGE_INTEGER ull;
  229. ull.LowPart = fad.ftLastWriteTime.dwLowDateTime;
  230. ull.HighPart = fad.ftLastWriteTime.dwHighDateTime;
  231. return (std::time_t) ((ull.QuadPart / 10000000ULL) - 11644473600ULL);
  232. }
  233. DataStreamPtr FileSystem::openFile(const Path& fullPath, bool readOnly)
  234. {
  235. WString pathWString = fullPath.toWString();
  236. const wchar_t* pathString = pathWString.c_str();
  237. if (!win32_pathExists(pathString) || !win32_isFile(pathString))
  238. {
  239. LOGWRN("Attempting to open a file that doesn't exist: " + fullPath.toString());
  240. return nullptr;
  241. }
  242. UINT64 fileSize = getFileSize(fullPath);
  243. // Always open in binary mode
  244. // Also, always include reading
  245. std::ios::openmode mode = std::ios::in | std::ios::binary;
  246. std::shared_ptr<std::istream> baseStream = 0;
  247. std::shared_ptr<std::ifstream> roStream = 0;
  248. std::shared_ptr<std::fstream> rwStream = 0;
  249. if (!readOnly)
  250. {
  251. mode |= std::ios::out;
  252. rwStream = bs_shared_ptr_new<std::fstream>();
  253. rwStream->open(pathString, mode);
  254. baseStream = rwStream;
  255. }
  256. else
  257. {
  258. roStream = bs_shared_ptr_new<std::ifstream>();
  259. roStream->open(pathString, mode);
  260. baseStream = roStream;
  261. }
  262. // Should check ensure open succeeded, in case fail for some reason.
  263. if (baseStream->fail())
  264. {
  265. LOGWRN("Cannot open file: " + fullPath.toString());
  266. return nullptr;
  267. }
  268. /// Construct return stream, tell it to delete on destroy
  269. FileDataStream* stream = 0;
  270. if (rwStream)
  271. {
  272. // use the writeable stream
  273. stream = bs_new<FileDataStream>(rwStream, (size_t)fileSize, true);
  274. }
  275. else
  276. {
  277. // read-only stream
  278. stream = bs_new<FileDataStream>(roStream, (size_t)fileSize, true);
  279. }
  280. return bs_shared_ptr<FileDataStream>(stream);
  281. }
  282. DataStreamPtr FileSystem::createAndOpenFile(const Path& fullPath)
  283. {
  284. // Always open in binary mode
  285. // Also, always include reading
  286. std::ios::openmode mode = std::ios::out | std::ios::binary;
  287. std::shared_ptr<std::fstream> rwStream = bs_shared_ptr_new<std::fstream>();
  288. rwStream->open(fullPath.toWString().c_str(), mode);
  289. // Should check ensure open succeeded, in case fail for some reason.
  290. if (rwStream->fail())
  291. BS_EXCEPT(FileNotFoundException, "Cannot open file: " + fullPath.toString());
  292. /// Construct return stream, tell it to delete on destroy
  293. return bs_shared_ptr_new<FileDataStream>(rwStream, 0, true);
  294. }
  295. UINT64 FileSystem::getFileSize(const Path& fullPath)
  296. {
  297. return win32_getFileSize(fullPath.toWString());
  298. }
  299. void FileSystem::remove(const Path& fullPath, bool recursively)
  300. {
  301. WString fullPathStr = fullPath.toWString();
  302. if (!FileSystem::exists(fullPath))
  303. return;
  304. if (recursively)
  305. {
  306. Vector<Path> files;
  307. Vector<Path> directories;
  308. getChildren(fullPath, files, directories);
  309. for (auto& file : files)
  310. remove(file, false);
  311. for (auto& dir : directories)
  312. remove(dir, true);
  313. }
  314. win32_remove(fullPathStr);
  315. }
  316. void FileSystem::move(const Path& oldPath, const Path& newPath, bool overwriteExisting)
  317. {
  318. WString oldPathStr = oldPath.toWString();
  319. WString newPathStr = newPath.toWString();
  320. if (win32_pathExists(newPathStr))
  321. {
  322. if (overwriteExisting)
  323. win32_remove(newPathStr);
  324. else
  325. {
  326. LOGWRN("Move operation failed because another file already exists at the new path: \"" + toString(newPathStr) + "\"");
  327. return;
  328. }
  329. }
  330. win32_rename(oldPathStr, newPathStr);
  331. }
  332. void FileSystem::copy(const Path& oldPath, const Path& newPath, bool overwriteExisting)
  333. {
  334. Stack<std::tuple<Path, Path>> todo;
  335. todo.push(std::make_tuple(oldPath, newPath));
  336. while (!todo.empty())
  337. {
  338. auto current = todo.top();
  339. todo.pop();
  340. Path sourcePath = std::get<0>(current);
  341. WString sourcePathStr = sourcePath.toWString();
  342. if (!win32_pathExists(sourcePathStr))
  343. continue;
  344. bool srcIsFile = win32_isFile(sourcePathStr);
  345. Path destinationPath = std::get<1>(current);
  346. WString destPathStr = destinationPath.toWString();
  347. bool destExists = win32_pathExists(destPathStr);
  348. if (destExists)
  349. {
  350. if (win32_isFile(destPathStr))
  351. {
  352. if (overwriteExisting)
  353. win32_remove(destPathStr);
  354. else
  355. {
  356. LOGWRN("Copy operation failed because another file already exists at the new path: \"" + toString(destPathStr) + "\"");
  357. return;
  358. }
  359. }
  360. }
  361. bool destIsFile = !destinationPath.getWExtension().empty();
  362. if (!srcIsFile && destIsFile)
  363. {
  364. LOGWRN("Cannot copy a source folder to a destination file.");
  365. return;
  366. }
  367. else if (srcIsFile && !destIsFile)
  368. {
  369. Path destinationFilePath = destinationPath;
  370. destinationFilePath.append(sourcePath.getWTail());
  371. win32_copyFile(sourcePathStr, destinationFilePath.toWString());
  372. }
  373. else if (srcIsFile && destIsFile)
  374. {
  375. win32_copyFile(sourcePathStr, destPathStr);
  376. }
  377. else if (!srcIsFile && !destIsFile)
  378. {
  379. if (!destExists)
  380. win32_createDirectory(destPathStr);
  381. Vector<Path> files;
  382. Vector<Path> directories;
  383. getChildren(destinationPath, files, directories);
  384. for (auto& file : files)
  385. {
  386. Path fileDestPath = destinationPath;
  387. fileDestPath.append(file.getWTail());
  388. todo.push(std::make_tuple(file, fileDestPath));
  389. }
  390. for (auto& dir : directories)
  391. {
  392. Path dirDestPath = destinationPath;
  393. dirDestPath.append(dir.getWTail());
  394. todo.push(std::make_tuple(dir, dirDestPath));
  395. }
  396. }
  397. }
  398. }
  399. bool FileSystem::exists(const Path& fullPath)
  400. {
  401. return win32_pathExists(fullPath.toWString());
  402. }
  403. bool FileSystem::isFile(const Path& fullPath)
  404. {
  405. WString pathStr = fullPath.toWString();
  406. return win32_pathExists(pathStr) && win32_isFile(pathStr);
  407. }
  408. bool FileSystem::isDirectory(const Path& fullPath)
  409. {
  410. WString pathStr = fullPath.toWString();
  411. return win32_pathExists(pathStr) && win32_isDirectory(pathStr);
  412. }
  413. void FileSystem::createDir(const Path& fullPath)
  414. {
  415. Path parentPath = fullPath;
  416. while (!exists(parentPath) && parentPath.getNumDirectories() > 0)
  417. {
  418. parentPath = parentPath.getParent();
  419. }
  420. for (UINT32 i = parentPath.getNumDirectories(); i < fullPath.getNumDirectories(); i++)
  421. {
  422. parentPath.append(fullPath[i]);
  423. win32_createDirectory(parentPath.toWString());
  424. }
  425. if (fullPath.isFile())
  426. win32_createDirectory(fullPath.toWString());
  427. }
  428. void FileSystem::getChildren(const Path& dirPath, Vector<Path>& files, Vector<Path>& directories)
  429. {
  430. if (dirPath.isFile())
  431. return;
  432. WString findPath = dirPath.toWString();
  433. findPath.append(L"*");
  434. WIN32_FIND_DATAW findData;
  435. HANDLE fileHandle = FindFirstFileW(findPath.c_str(), &findData);
  436. bool lastFailed = false;
  437. WString tempName;
  438. do
  439. {
  440. if (lastFailed || fileHandle == INVALID_HANDLE_VALUE)
  441. {
  442. if (GetLastError() == ERROR_NO_MORE_FILES)
  443. break;
  444. else
  445. win32_handleError(GetLastError(), findPath);
  446. }
  447. else
  448. {
  449. tempName = findData.cFileName;
  450. if (tempName != L"." && tempName != L"..")
  451. {
  452. Path fullPath = dirPath;
  453. if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
  454. directories.push_back(fullPath.append(tempName + L"/"));
  455. else
  456. files.push_back(fullPath.append(tempName));
  457. }
  458. }
  459. lastFailed = FindNextFileW(fileHandle, &findData) == FALSE;
  460. } while (true);
  461. FindClose(fileHandle);
  462. }
  463. bool FileSystem::iterate(const Path& dirPath, std::function<bool(const Path&)> fileCallback,
  464. std::function<bool(const Path&)> dirCallback, bool recursive)
  465. {
  466. if (dirPath.isFile())
  467. return true;
  468. WString findPath = dirPath.toWString();
  469. findPath.append(L"*");
  470. WIN32_FIND_DATAW findData;
  471. HANDLE fileHandle = FindFirstFileW(findPath.c_str(), &findData);
  472. bool lastFailed = false;
  473. WString tempName;
  474. do
  475. {
  476. if (lastFailed || fileHandle == INVALID_HANDLE_VALUE)
  477. {
  478. if (GetLastError() != ERROR_NO_MORE_FILES)
  479. win32_handleError(GetLastError(), findPath);
  480. break;
  481. }
  482. else
  483. {
  484. tempName = findData.cFileName;
  485. if (tempName != L"." && tempName != L"..")
  486. {
  487. Path fullPath = dirPath;
  488. if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
  489. {
  490. Path childDir = fullPath.append(tempName + L"/");
  491. if (dirCallback != nullptr)
  492. {
  493. if (!dirCallback(childDir))
  494. {
  495. FindClose(fileHandle);
  496. return false;
  497. }
  498. }
  499. if (recursive)
  500. {
  501. if (!iterate(childDir, fileCallback, dirCallback, recursive))
  502. {
  503. FindClose(fileHandle);
  504. return false;
  505. }
  506. }
  507. }
  508. else
  509. {
  510. Path filePath = fullPath.append(tempName);
  511. if (fileCallback != nullptr)
  512. {
  513. if (!fileCallback(filePath))
  514. {
  515. FindClose(fileHandle);
  516. return false;
  517. }
  518. }
  519. }
  520. }
  521. }
  522. lastFailed = FindNextFileW(fileHandle, &findData) == FALSE;
  523. } while (true);
  524. FindClose(fileHandle);
  525. return true;
  526. }
  527. std::time_t FileSystem::getLastModifiedTime(const Path& fullPath)
  528. {
  529. return win32_getLastModifiedTime(fullPath.toWString().c_str());
  530. }
  531. Path FileSystem::getWorkingDirectoryPath()
  532. {
  533. return Path(win32_getCurrentDirectory());
  534. }
  535. Path FileSystem::getTempDirectoryPath()
  536. {
  537. return Path(win32_getTempDirectory());
  538. }
  539. }