BsFileSystem.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. //__________________________ Banshee Project - A modern game development toolkit _________________________________//
  2. //_____________________________________ www.banshee-project.com __________________________________________________//
  3. //________________________ Copyright (c) 2014 Marko Pintera. All rights reserved. ________________________________//
  4. #include "BsFileSystem.h"
  5. #include "BsException.h"
  6. #include "BsDataStream.h"
  7. #include "BsPath.h"
  8. #include <windows.h>
  9. namespace BansheeEngine
  10. {
  11. void win32_handleError(DWORD error, const WString& path)
  12. {
  13. switch (error)
  14. {
  15. case ERROR_FILE_NOT_FOUND:
  16. BS_EXCEPT(FileNotFoundException, "File at path: \"" + toString(path) + "\" not found.");
  17. case ERROR_PATH_NOT_FOUND:
  18. case ERROR_BAD_NETPATH:
  19. case ERROR_CANT_RESOLVE_FILENAME:
  20. case ERROR_INVALID_DRIVE:
  21. BS_EXCEPT(FileNotFoundException, "Path \"" + toString(path) + "\" not found.");
  22. case ERROR_ACCESS_DENIED:
  23. BS_EXCEPT(IOException, "Access to path \"" + toString(path) + "\" denied.");
  24. case ERROR_ALREADY_EXISTS:
  25. case ERROR_FILE_EXISTS:
  26. BS_EXCEPT(IOException, "File/folder at path \"" + toString(path) + "\" already exists.");
  27. case ERROR_INVALID_NAME:
  28. case ERROR_DIRECTORY:
  29. case ERROR_FILENAME_EXCED_RANGE:
  30. case ERROR_BAD_PATHNAME:
  31. BS_EXCEPT(IOException, "Invalid path string: \"" + toString(path) + "\".");
  32. case ERROR_FILE_READ_ONLY:
  33. BS_EXCEPT(IOException, "File at path \"" + toString(path) + "\" is read only.");
  34. case ERROR_CANNOT_MAKE:
  35. BS_EXCEPT(IOException, "Cannot create file/folder at path: \"" + toString(path) + "\".");
  36. case ERROR_DIR_NOT_EMPTY:
  37. BS_EXCEPT(IOException, "Directory at path \"" + toString(path) + "\" not empty.");
  38. case ERROR_WRITE_FAULT:
  39. BS_EXCEPT(IOException, "Error while writing a file at path \"" + toString(path) + "\".");
  40. case ERROR_READ_FAULT:
  41. BS_EXCEPT(IOException, "Error while reading a file at path \"" + toString(path) + "\".");
  42. case ERROR_SHARING_VIOLATION:
  43. BS_EXCEPT(IOException, "Sharing violation at path \"" + toString(path) + "\".");
  44. case ERROR_LOCK_VIOLATION:
  45. BS_EXCEPT(IOException, "Lock violation at path \"" + toString(path) + "\".");
  46. case ERROR_HANDLE_EOF:
  47. BS_EXCEPT(IOException, "End of file reached for file at path \"" + toString(path) + "\".");
  48. case ERROR_HANDLE_DISK_FULL:
  49. case ERROR_DISK_FULL:
  50. BS_EXCEPT(IOException, "Disk full.");
  51. case ERROR_NEGATIVE_SEEK:
  52. BS_EXCEPT(IOException, "Negative seek.");
  53. default:
  54. BS_EXCEPT(IOException, "Undefined file system exception.");
  55. }
  56. }
  57. WString win32_getCurrentDirectory()
  58. {
  59. DWORD len = GetCurrentDirectoryW(0, NULL);
  60. if (len > 0)
  61. {
  62. wchar_t* buffer = (wchar_t*)bs_alloc(len * sizeof(wchar_t));
  63. DWORD n = GetCurrentDirectoryW(len, buffer);
  64. if (n > 0 && n <= len)
  65. {
  66. WString result(buffer);
  67. if (result[result.size() - 1] != '\\')
  68. result.append(L"\\");
  69. bs_free(buffer);
  70. return result;
  71. }
  72. bs_free(buffer);
  73. }
  74. return StringUtil::WBLANK;
  75. }
  76. bool win32_pathExists(const WString& path)
  77. {
  78. DWORD attr = GetFileAttributesW(path.c_str());
  79. if (attr == 0xFFFFFFFF)
  80. {
  81. switch (GetLastError())
  82. {
  83. case ERROR_FILE_NOT_FOUND:
  84. case ERROR_PATH_NOT_FOUND:
  85. case ERROR_NOT_READY:
  86. case ERROR_INVALID_DRIVE:
  87. return false;
  88. default:
  89. win32_handleError(GetLastError(), path);
  90. }
  91. }
  92. return true;
  93. }
  94. bool win32_isDirectory(const WString& path)
  95. {
  96. DWORD attr = GetFileAttributesW(path.c_str());
  97. if (attr == 0xFFFFFFFF)
  98. win32_handleError(GetLastError(), path);
  99. return (attr & FILE_ATTRIBUTE_DIRECTORY) != FALSE;
  100. }
  101. bool win32_isDevice(const WString& path)
  102. {
  103. WString ucPath = path;
  104. StringUtil::toUpperCase(ucPath);
  105. return
  106. ucPath.compare(0, 4, L"\\\\.\\") == 0 ||
  107. ucPath.compare(L"CON") == 0 ||
  108. ucPath.compare(L"PRN") == 0 ||
  109. ucPath.compare(L"AUX") == 0 ||
  110. ucPath.compare(L"NUL") == 0 ||
  111. ucPath.compare(L"LPT1") == 0 ||
  112. ucPath.compare(L"LPT2") == 0 ||
  113. ucPath.compare(L"LPT3") == 0 ||
  114. ucPath.compare(L"LPT4") == 0 ||
  115. ucPath.compare(L"LPT5") == 0 ||
  116. ucPath.compare(L"LPT6") == 0 ||
  117. ucPath.compare(L"LPT7") == 0 ||
  118. ucPath.compare(L"LPT8") == 0 ||
  119. ucPath.compare(L"LPT9") == 0 ||
  120. ucPath.compare(L"COM1") == 0 ||
  121. ucPath.compare(L"COM2") == 0 ||
  122. ucPath.compare(L"COM3") == 0 ||
  123. ucPath.compare(L"COM4") == 0 ||
  124. ucPath.compare(L"COM5") == 0 ||
  125. ucPath.compare(L"COM6") == 0 ||
  126. ucPath.compare(L"COM7") == 0 ||
  127. ucPath.compare(L"COM8") == 0 ||
  128. ucPath.compare(L"COM9") == 0;
  129. }
  130. bool win32_isFile(const WString& path)
  131. {
  132. return !win32_isDirectory(path) && !win32_isDevice(path);
  133. }
  134. bool win32_createFile(const WString& path)
  135. {
  136. HANDLE hFile = CreateFileW(path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0);
  137. if (hFile != INVALID_HANDLE_VALUE)
  138. {
  139. CloseHandle(hFile);
  140. return true;
  141. }
  142. else if (GetLastError() == ERROR_FILE_EXISTS)
  143. return false;
  144. else
  145. win32_handleError(GetLastError(), path);
  146. return false;
  147. }
  148. bool win32_createDirectory(const WString& path)
  149. {
  150. if (win32_pathExists(path) && win32_isDirectory(path))
  151. return false;
  152. if (CreateDirectoryW(path.c_str(), 0) == FALSE)
  153. win32_handleError(GetLastError(), path);
  154. return true;
  155. }
  156. void win32_remove(const WString& path)
  157. {
  158. if (win32_isDirectory(path))
  159. {
  160. if (RemoveDirectoryW(path.c_str()) == 0)
  161. win32_handleError(GetLastError(), path);
  162. }
  163. else
  164. {
  165. if (DeleteFileW(path.c_str()) == 0)
  166. win32_handleError(GetLastError(), path);
  167. }
  168. }
  169. void win32_copy(const WString& from, const WString& to)
  170. {
  171. if (CopyFileW(from.c_str(), to.c_str(), FALSE) == FALSE)
  172. win32_handleError(GetLastError(), from);
  173. }
  174. void win32_rename(const WString& oldPath, const WString& newPath)
  175. {
  176. if (MoveFileW(oldPath.c_str(), newPath.c_str()) == 0)
  177. win32_handleError(GetLastError(), oldPath);
  178. }
  179. UINT64 win32_getFileSize(const WString& path)
  180. {
  181. WIN32_FILE_ATTRIBUTE_DATA attrData;
  182. if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &attrData) == FALSE)
  183. win32_handleError(GetLastError(), path);
  184. LARGE_INTEGER li;
  185. li.LowPart = attrData.nFileSizeLow;
  186. li.HighPart = attrData.nFileSizeHigh;
  187. return (UINT64)li.QuadPart;
  188. }
  189. std::time_t win32_getLastModifiedTime(const WString& path)
  190. {
  191. WIN32_FILE_ATTRIBUTE_DATA fad;
  192. if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &fad) == 0)
  193. win32_handleError(GetLastError(), path);
  194. ULARGE_INTEGER ull;
  195. ull.LowPart = fad.ftLastWriteTime.dwLowDateTime;
  196. ull.HighPart = fad.ftLastWriteTime.dwHighDateTime;
  197. return (std::time_t) ((ull.QuadPart / 10000000ULL) - 11644473600ULL);
  198. }
  199. DataStreamPtr FileSystem::openFile(const Path& fullPath, bool readOnly)
  200. {
  201. UINT64 fileSize = getFileSize(fullPath);
  202. // Always open in binary mode
  203. // Also, always include reading
  204. std::ios::openmode mode = std::ios::in | std::ios::binary;
  205. std::shared_ptr<std::istream> baseStream = 0;
  206. std::shared_ptr<std::ifstream> roStream = 0;
  207. std::shared_ptr<std::fstream> rwStream = 0;
  208. if (!readOnly)
  209. {
  210. mode |= std::ios::out;
  211. rwStream = bs_shared_ptr<std::fstream, ScratchAlloc>();
  212. rwStream->open(fullPath.toWString().c_str(), mode);
  213. baseStream = rwStream;
  214. }
  215. else
  216. {
  217. roStream = bs_shared_ptr<std::ifstream, ScratchAlloc>();
  218. roStream->open(fullPath.toWString().c_str(), mode);
  219. baseStream = roStream;
  220. }
  221. // Should check ensure open succeeded, in case fail for some reason.
  222. if (baseStream->fail())
  223. BS_EXCEPT(FileNotFoundException, "Cannot open file: " + fullPath.toString());
  224. /// Construct return stream, tell it to delete on destroy
  225. FileDataStream* stream = 0;
  226. if (rwStream)
  227. {
  228. // use the writeable stream
  229. stream = bs_new<FileDataStream, ScratchAlloc>(rwStream, (size_t)fileSize, true);
  230. }
  231. else
  232. {
  233. // read-only stream
  234. stream = bs_new<FileDataStream, ScratchAlloc>(roStream, (size_t)fileSize, true);
  235. }
  236. return bs_shared_ptr<FileDataStream, ScratchAlloc>(stream);
  237. }
  238. DataStreamPtr FileSystem::createAndOpenFile(const Path& fullPath)
  239. {
  240. // Always open in binary mode
  241. // Also, always include reading
  242. std::ios::openmode mode = std::ios::out | std::ios::binary;
  243. std::shared_ptr<std::fstream> rwStream = bs_shared_ptr<std::fstream, ScratchAlloc>();
  244. rwStream->open(fullPath.toWString().c_str(), mode);
  245. // Should check ensure open succeeded, in case fail for some reason.
  246. if (rwStream->fail())
  247. BS_EXCEPT(FileNotFoundException, "Cannot open file: " + fullPath.toString());
  248. /// Construct return stream, tell it to delete on destroy
  249. return bs_shared_ptr<FileDataStream, ScratchAlloc>(rwStream, 0, true);
  250. }
  251. UINT64 FileSystem::getFileSize(const Path& fullPath)
  252. {
  253. return win32_getFileSize(fullPath.toWString());
  254. }
  255. void FileSystem::remove(const Path& fullPath, bool recursively)
  256. {
  257. WString fullPathStr = fullPath.toWString();
  258. if (recursively)
  259. {
  260. Vector<Path> files;
  261. Vector<Path> directories;
  262. getChildren(fullPath, files, directories);
  263. for (auto& file : files)
  264. remove(file, false);
  265. for (auto& dir : directories)
  266. remove(dir, true);
  267. }
  268. win32_remove(fullPathStr);
  269. }
  270. void FileSystem::move(const Path& oldPath, const Path& newPath, bool overwriteExisting)
  271. {
  272. WString oldPathStr = oldPath.toWString();
  273. WString newPathStr = newPath.toWString();
  274. if (win32_pathExists(newPathStr))
  275. {
  276. if (overwriteExisting)
  277. win32_remove(newPathStr);
  278. else
  279. {
  280. BS_EXCEPT(InvalidStateException, "Move operation failed because another file already exists at the new path: \"" + toString(newPathStr) + "\"");
  281. }
  282. }
  283. win32_rename(oldPathStr, newPathStr);
  284. }
  285. bool FileSystem::exists(const Path& fullPath)
  286. {
  287. return win32_pathExists(fullPath.toWString());
  288. }
  289. bool FileSystem::isFile(const Path& fullPath)
  290. {
  291. WString pathStr = fullPath.toWString();
  292. return win32_pathExists(pathStr) && win32_isFile(pathStr);
  293. }
  294. bool FileSystem::isDirectory(const Path& fullPath)
  295. {
  296. WString pathStr = fullPath.toWString();
  297. return win32_pathExists(pathStr) && win32_isDirectory(pathStr);
  298. }
  299. void FileSystem::createDir(const Path& fullPath)
  300. {
  301. Path parentPath = fullPath;
  302. while (!exists(parentPath))
  303. {
  304. parentPath = parentPath.getParent();
  305. }
  306. for (UINT32 i = parentPath.getNumDirectories(); i < fullPath.getNumDirectories(); i++)
  307. {
  308. win32_createDirectory(parentPath.toWString());
  309. parentPath.append(fullPath[i]);
  310. }
  311. }
  312. void FileSystem::getChildren(const Path& dirPath, Vector<Path>& files, Vector<Path>& directories)
  313. {
  314. if (dirPath.isFile())
  315. return;
  316. WString findPath = dirPath.toWString();
  317. findPath.append(L"*");
  318. WIN32_FIND_DATAW findData;
  319. HANDLE fileHandle = FindFirstFileW(findPath.c_str(), &findData);
  320. bool lastFailed = false;
  321. WString tempName;
  322. do
  323. {
  324. if (lastFailed || fileHandle == INVALID_HANDLE_VALUE)
  325. {
  326. if (GetLastError() == ERROR_NO_MORE_FILES)
  327. break;
  328. else
  329. win32_handleError(GetLastError(), findPath);
  330. }
  331. else
  332. {
  333. tempName = findData.cFileName;
  334. if (tempName != L"." && tempName != L"..")
  335. {
  336. Path fullPath = dirPath;
  337. if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
  338. directories.push_back(fullPath.append(tempName));
  339. else
  340. files.push_back(fullPath.append(tempName));
  341. }
  342. }
  343. lastFailed = FindNextFileW(fileHandle, &findData) == FALSE;
  344. } while (true);
  345. }
  346. std::time_t FileSystem::getLastModifiedTime(const Path& fullPath)
  347. {
  348. return win32_getLastModifiedTime(fullPath.toWString().c_str());
  349. }
  350. Path FileSystem::getWorkingDirectoryPath()
  351. {
  352. return Path(win32_getCurrentDirectory());
  353. }
  354. }