BsFileSystem.cpp 13 KB

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