BsWin32FileSystem.cpp 15 KB

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