BsFileSystem.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. bool win32_pathExists(const WString& path)
  73. {
  74. DWORD attr = GetFileAttributesW(path.c_str());
  75. if (attr == 0xFFFFFFFF)
  76. {
  77. switch (GetLastError())
  78. {
  79. case ERROR_FILE_NOT_FOUND:
  80. case ERROR_PATH_NOT_FOUND:
  81. case ERROR_NOT_READY:
  82. case ERROR_INVALID_DRIVE:
  83. return false;
  84. default:
  85. win32_handleError(GetLastError(), path);
  86. }
  87. }
  88. return true;
  89. }
  90. bool win32_isDirectory(const WString& path)
  91. {
  92. DWORD attr = GetFileAttributesW(path.c_str());
  93. if (attr == 0xFFFFFFFF)
  94. win32_handleError(GetLastError(), path);
  95. return (attr & FILE_ATTRIBUTE_DIRECTORY) != FALSE;
  96. }
  97. bool win32_isDevice(const WString& path)
  98. {
  99. WString ucPath = path;
  100. StringUtil::toUpperCase(ucPath);
  101. return
  102. ucPath.compare(0, 4, L"\\\\.\\") == 0 ||
  103. ucPath.compare(L"CON") == 0 ||
  104. ucPath.compare(L"PRN") == 0 ||
  105. ucPath.compare(L"AUX") == 0 ||
  106. ucPath.compare(L"NUL") == 0 ||
  107. ucPath.compare(L"LPT1") == 0 ||
  108. ucPath.compare(L"LPT2") == 0 ||
  109. ucPath.compare(L"LPT3") == 0 ||
  110. ucPath.compare(L"LPT4") == 0 ||
  111. ucPath.compare(L"LPT5") == 0 ||
  112. ucPath.compare(L"LPT6") == 0 ||
  113. ucPath.compare(L"LPT7") == 0 ||
  114. ucPath.compare(L"LPT8") == 0 ||
  115. ucPath.compare(L"LPT9") == 0 ||
  116. ucPath.compare(L"COM1") == 0 ||
  117. ucPath.compare(L"COM2") == 0 ||
  118. ucPath.compare(L"COM3") == 0 ||
  119. ucPath.compare(L"COM4") == 0 ||
  120. ucPath.compare(L"COM5") == 0 ||
  121. ucPath.compare(L"COM6") == 0 ||
  122. ucPath.compare(L"COM7") == 0 ||
  123. ucPath.compare(L"COM8") == 0 ||
  124. ucPath.compare(L"COM9") == 0;
  125. }
  126. bool win32_isFile(const WString& path)
  127. {
  128. return !win32_isDirectory(path) && !win32_isDevice(path);
  129. }
  130. bool win32_createFile(const WString& path)
  131. {
  132. HANDLE hFile = CreateFileW(path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0);
  133. if (hFile != INVALID_HANDLE_VALUE)
  134. {
  135. CloseHandle(hFile);
  136. return true;
  137. }
  138. else if (GetLastError() == ERROR_FILE_EXISTS)
  139. return false;
  140. else
  141. win32_handleError(GetLastError(), path);
  142. return false;
  143. }
  144. bool win32_createDirectory(const WString& path)
  145. {
  146. if (win32_pathExists(path) && win32_isDirectory(path))
  147. return false;
  148. if (CreateDirectoryW(path.c_str(), 0) == FALSE)
  149. win32_handleError(GetLastError(), path);
  150. return true;
  151. }
  152. void win32_remove(const WString& path)
  153. {
  154. if (win32_isDirectory(path))
  155. {
  156. if (RemoveDirectoryW(path.c_str()) == 0)
  157. win32_handleError(GetLastError(), path);
  158. }
  159. else
  160. {
  161. if (DeleteFileW(path.c_str()) == 0)
  162. win32_handleError(GetLastError(), path);
  163. }
  164. }
  165. void win32_copyFile(const WString& from, const WString& to)
  166. {
  167. if (CopyFileW(from.c_str(), to.c_str(), FALSE) == FALSE)
  168. win32_handleError(GetLastError(), from);
  169. }
  170. void win32_rename(const WString& oldPath, const WString& newPath)
  171. {
  172. if (MoveFileW(oldPath.c_str(), newPath.c_str()) == 0)
  173. win32_handleError(GetLastError(), oldPath);
  174. }
  175. UINT64 win32_getFileSize(const WString& path)
  176. {
  177. WIN32_FILE_ATTRIBUTE_DATA attrData;
  178. if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &attrData) == FALSE)
  179. win32_handleError(GetLastError(), path);
  180. LARGE_INTEGER li;
  181. li.LowPart = attrData.nFileSizeLow;
  182. li.HighPart = attrData.nFileSizeHigh;
  183. return (UINT64)li.QuadPart;
  184. }
  185. std::time_t win32_getLastModifiedTime(const WString& path)
  186. {
  187. WIN32_FILE_ATTRIBUTE_DATA fad;
  188. if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &fad) == 0)
  189. win32_handleError(GetLastError(), path);
  190. ULARGE_INTEGER ull;
  191. ull.LowPart = fad.ftLastWriteTime.dwLowDateTime;
  192. ull.HighPart = fad.ftLastWriteTime.dwHighDateTime;
  193. return (std::time_t) ((ull.QuadPart / 10000000ULL) - 11644473600ULL);
  194. }
  195. DataStreamPtr FileSystem::openFile(const Path& fullPath, bool readOnly)
  196. {
  197. UINT64 fileSize = getFileSize(fullPath);
  198. // Always open in binary mode
  199. // Also, always include reading
  200. std::ios::openmode mode = std::ios::in | std::ios::binary;
  201. std::shared_ptr<std::istream> baseStream = 0;
  202. std::shared_ptr<std::ifstream> roStream = 0;
  203. std::shared_ptr<std::fstream> rwStream = 0;
  204. if (!readOnly)
  205. {
  206. mode |= std::ios::out;
  207. rwStream = bs_shared_ptr<std::fstream, ScratchAlloc>();
  208. rwStream->open(fullPath.toWString().c_str(), mode);
  209. baseStream = rwStream;
  210. }
  211. else
  212. {
  213. roStream = bs_shared_ptr<std::ifstream, ScratchAlloc>();
  214. roStream->open(fullPath.toWString().c_str(), mode);
  215. baseStream = roStream;
  216. }
  217. // Should check ensure open succeeded, in case fail for some reason.
  218. if (baseStream->fail())
  219. BS_EXCEPT(FileNotFoundException, "Cannot open file: " + fullPath.toString());
  220. /// Construct return stream, tell it to delete on destroy
  221. FileDataStream* stream = 0;
  222. if (rwStream)
  223. {
  224. // use the writeable stream
  225. stream = bs_new<FileDataStream, ScratchAlloc>(rwStream, (size_t)fileSize, true);
  226. }
  227. else
  228. {
  229. // read-only stream
  230. stream = bs_new<FileDataStream, ScratchAlloc>(roStream, (size_t)fileSize, true);
  231. }
  232. return bs_shared_ptr<FileDataStream, ScratchAlloc>(stream);
  233. }
  234. DataStreamPtr FileSystem::createAndOpenFile(const Path& fullPath)
  235. {
  236. // Always open in binary mode
  237. // Also, always include reading
  238. std::ios::openmode mode = std::ios::out | std::ios::binary;
  239. std::shared_ptr<std::fstream> rwStream = bs_shared_ptr<std::fstream, ScratchAlloc>();
  240. rwStream->open(fullPath.toWString().c_str(), mode);
  241. // Should check ensure open succeeded, in case fail for some reason.
  242. if (rwStream->fail())
  243. BS_EXCEPT(FileNotFoundException, "Cannot open file: " + fullPath.toString());
  244. /// Construct return stream, tell it to delete on destroy
  245. return bs_shared_ptr<FileDataStream, ScratchAlloc>(rwStream, 0, true);
  246. }
  247. UINT64 FileSystem::getFileSize(const Path& fullPath)
  248. {
  249. return win32_getFileSize(fullPath.toWString());
  250. }
  251. void FileSystem::remove(const Path& fullPath, bool recursively)
  252. {
  253. WString fullPathStr = fullPath.toWString();
  254. if (!FileSystem::exists(fullPath))
  255. return;
  256. if (recursively)
  257. {
  258. Vector<Path> files;
  259. Vector<Path> directories;
  260. getChildren(fullPath, files, directories);
  261. for (auto& file : files)
  262. remove(file, false);
  263. for (auto& dir : directories)
  264. remove(dir, true);
  265. }
  266. win32_remove(fullPathStr);
  267. }
  268. void FileSystem::move(const Path& oldPath, const Path& newPath, bool overwriteExisting)
  269. {
  270. WString oldPathStr = oldPath.toWString();
  271. WString newPathStr = newPath.toWString();
  272. if (win32_pathExists(newPathStr))
  273. {
  274. if (overwriteExisting)
  275. win32_remove(newPathStr);
  276. else
  277. {
  278. BS_EXCEPT(InvalidStateException, "Move operation failed because another file already exists at the new path: \"" + toString(newPathStr) + "\"");
  279. }
  280. }
  281. win32_rename(oldPathStr, newPathStr);
  282. }
  283. void FileSystem::copy(const Path& oldPath, const Path& newPath, bool overwriteExisting)
  284. {
  285. Stack<std::tuple<Path, Path>> todo;
  286. todo.push(std::make_tuple(oldPath, newPath));
  287. while (!todo.empty())
  288. {
  289. auto current = todo.top();
  290. todo.pop();
  291. Path sourcePath = std::get<0>(current);
  292. WString sourcePathStr = sourcePath.toWString();
  293. if (!win32_pathExists(sourcePathStr))
  294. continue;
  295. bool srcIsFile = win32_isFile(sourcePathStr);
  296. Path destinationPath = std::get<1>(current);
  297. WString destPathStr = destinationPath.toWString();
  298. bool destExists = win32_pathExists(destPathStr);
  299. if (destExists)
  300. {
  301. if (win32_isFile(destPathStr))
  302. {
  303. if (overwriteExisting)
  304. win32_remove(destPathStr);
  305. else
  306. {
  307. BS_EXCEPT(InvalidStateException, "Copy operation failed because another file already exists at the new path: \"" + toString(destPathStr) + "\"");
  308. }
  309. }
  310. }
  311. bool destIsFile = !destinationPath.getWExtension().empty();
  312. if (!srcIsFile && destIsFile)
  313. {
  314. BS_EXCEPT(InvalidStateException, "Cannot copy a source folder to a destination file.");
  315. }
  316. else if (srcIsFile && !destIsFile)
  317. {
  318. Path destinationFilePath = destinationPath;
  319. destinationFilePath.append(sourcePath.getWTail());
  320. win32_copyFile(sourcePathStr, destinationFilePath.toWString());
  321. }
  322. else if (srcIsFile && destIsFile)
  323. {
  324. win32_copyFile(sourcePathStr, destPathStr);
  325. }
  326. else if (!srcIsFile && !destIsFile)
  327. {
  328. if (!destExists)
  329. win32_createDirectory(destPathStr);
  330. Vector<Path> files;
  331. Vector<Path> directories;
  332. getChildren(destinationPath, files, directories);
  333. for (auto& file : files)
  334. {
  335. Path fileDestPath = destinationPath;
  336. fileDestPath.append(file.getWTail());
  337. todo.push(std::make_tuple(file, fileDestPath));
  338. }
  339. for (auto& dir : directories)
  340. {
  341. Path dirDestPath = destinationPath;
  342. dirDestPath.append(dir.getWTail());
  343. todo.push(std::make_tuple(dir, dirDestPath));
  344. }
  345. }
  346. }
  347. }
  348. bool FileSystem::exists(const Path& fullPath)
  349. {
  350. return win32_pathExists(fullPath.toWString());
  351. }
  352. bool FileSystem::isFile(const Path& fullPath)
  353. {
  354. WString pathStr = fullPath.toWString();
  355. return win32_pathExists(pathStr) && win32_isFile(pathStr);
  356. }
  357. bool FileSystem::isDirectory(const Path& fullPath)
  358. {
  359. WString pathStr = fullPath.toWString();
  360. return win32_pathExists(pathStr) && win32_isDirectory(pathStr);
  361. }
  362. void FileSystem::createDir(const Path& fullPath)
  363. {
  364. Path parentPath = fullPath;
  365. while (!exists(parentPath))
  366. {
  367. parentPath = parentPath.getParent();
  368. }
  369. for (UINT32 i = parentPath.getNumDirectories(); i < fullPath.getNumDirectories(); i++)
  370. {
  371. parentPath.append(fullPath[i]);
  372. win32_createDirectory(parentPath.toWString());
  373. }
  374. }
  375. void FileSystem::getChildren(const Path& dirPath, Vector<Path>& files, Vector<Path>& directories)
  376. {
  377. if (dirPath.isFile())
  378. return;
  379. WString findPath = dirPath.toWString();
  380. findPath.append(L"*");
  381. WIN32_FIND_DATAW findData;
  382. HANDLE fileHandle = FindFirstFileW(findPath.c_str(), &findData);
  383. bool lastFailed = false;
  384. WString tempName;
  385. do
  386. {
  387. if (lastFailed || fileHandle == INVALID_HANDLE_VALUE)
  388. {
  389. if (GetLastError() == ERROR_NO_MORE_FILES)
  390. break;
  391. else
  392. win32_handleError(GetLastError(), findPath);
  393. }
  394. else
  395. {
  396. tempName = findData.cFileName;
  397. if (tempName != L"." && tempName != L"..")
  398. {
  399. Path fullPath = dirPath;
  400. if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
  401. directories.push_back(fullPath.append(tempName + L"/"));
  402. else
  403. files.push_back(fullPath.append(tempName));
  404. }
  405. }
  406. lastFailed = FindNextFileW(fileHandle, &findData) == FALSE;
  407. } while (true);
  408. FindClose(fileHandle);
  409. }
  410. std::time_t FileSystem::getLastModifiedTime(const Path& fullPath)
  411. {
  412. return win32_getLastModifiedTime(fullPath.toWString().c_str());
  413. }
  414. Path FileSystem::getWorkingDirectoryPath()
  415. {
  416. return Path(win32_getCurrentDirectory());
  417. }
  418. }