BsFileSystem.cpp 15 KB

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