BsFileSystem.cpp 15 KB

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