CmFileSystem.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. #include "CmFileSystem.h"
  2. #include "CmException.h"
  3. #include "CmDataStream.h"
  4. #include "CmPath.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. CM_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. CM_EXCEPT(FileNotFoundException, "Path \"" + toString(path) + "\" not found.");
  19. case ERROR_ACCESS_DENIED:
  20. CM_EXCEPT(IOException, "Access to path \"" + toString(path) + "\" denied.");
  21. case ERROR_ALREADY_EXISTS:
  22. case ERROR_FILE_EXISTS:
  23. CM_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. CM_EXCEPT(IOException, "Invalid path string: \"" + toString(path) + "\".");
  29. case ERROR_FILE_READ_ONLY:
  30. CM_EXCEPT(IOException, "File at path \"" + toString(path) + "\" is read only.");
  31. case ERROR_CANNOT_MAKE:
  32. CM_EXCEPT(IOException, "Cannot create file/folder at path: \"" + toString(path) + "\".");
  33. case ERROR_DIR_NOT_EMPTY:
  34. CM_EXCEPT(IOException, "Directory at path \"" + toString(path) + "\" not empty.");
  35. case ERROR_WRITE_FAULT:
  36. CM_EXCEPT(IOException, "Error while writing a file at path \"" + toString(path) + "\".");
  37. case ERROR_READ_FAULT:
  38. CM_EXCEPT(IOException, "Error while reading a file at path \"" + toString(path) + "\".");
  39. case ERROR_SHARING_VIOLATION:
  40. CM_EXCEPT(IOException, "Sharing violation at path \"" + toString(path) + "\".");
  41. case ERROR_LOCK_VIOLATION:
  42. CM_EXCEPT(IOException, "Lock violation at path \"" + toString(path) + "\".");
  43. case ERROR_HANDLE_EOF:
  44. CM_EXCEPT(IOException, "End of file reached for file at path \"" + toString(path) + "\".");
  45. case ERROR_HANDLE_DISK_FULL:
  46. case ERROR_DISK_FULL:
  47. CM_EXCEPT(IOException, "Disk full.");
  48. case ERROR_NEGATIVE_SEEK:
  49. CM_EXCEPT(IOException, "Negative seek.");
  50. default:
  51. CM_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*)cm_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. cm_free(buffer);
  67. return result;
  68. }
  69. cm_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_copy(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 = cm_shared_ptr<std::fstream, ScratchAlloc>();
  209. rwStream->open(fullPath.toWString().c_str(), mode);
  210. baseStream = rwStream;
  211. }
  212. else
  213. {
  214. roStream = cm_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. CM_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 = cm_new<FileDataStream, ScratchAlloc>(rwStream, (size_t)fileSize, true);
  227. }
  228. else
  229. {
  230. // read-only stream
  231. stream = cm_new<FileDataStream, ScratchAlloc>(roStream, (size_t)fileSize, true);
  232. }
  233. return cm_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 = cm_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. CM_EXCEPT(FileNotFoundException, "Cannot open file: " + fullPath.toString());
  245. /// Construct return stream, tell it to delete on destroy
  246. return cm_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 (recursively)
  256. {
  257. Vector<Path>::type files;
  258. Vector<Path>::type directories;
  259. getChildren(fullPath, files, directories);
  260. for (auto& file : files)
  261. remove(file, false);
  262. for (auto& dir : directories)
  263. remove(dir, true);
  264. }
  265. win32_remove(fullPathStr);
  266. }
  267. void FileSystem::move(const Path& oldPath, const Path& newPath, bool overwriteExisting)
  268. {
  269. WString oldPathStr = oldPath.toWString();
  270. WString newPathStr = newPath.toWString();
  271. if (win32_pathExists(newPathStr))
  272. {
  273. if (overwriteExisting)
  274. win32_remove(newPathStr);
  275. else
  276. {
  277. CM_EXCEPT(InvalidStateException, "Move operation failed because another file already exists at the new path: \"" + toString(newPathStr) + "\"");
  278. }
  279. }
  280. win32_rename(oldPathStr, newPathStr);
  281. }
  282. bool FileSystem::exists(const Path& fullPath)
  283. {
  284. return win32_pathExists(fullPath.toWString());
  285. }
  286. bool FileSystem::isFile(const Path& fullPath)
  287. {
  288. WString pathStr = fullPath.toWString();
  289. return win32_pathExists(pathStr) && win32_isFile(pathStr);
  290. }
  291. bool FileSystem::isDirectory(const Path& fullPath)
  292. {
  293. WString pathStr = fullPath.toWString();
  294. return win32_pathExists(pathStr) && win32_isDirectory(pathStr);
  295. }
  296. void FileSystem::createDir(const Path& fullPath)
  297. {
  298. Path parentPath = fullPath;
  299. while (!exists(parentPath))
  300. {
  301. parentPath = parentPath.getParent();
  302. }
  303. for (UINT32 i = parentPath.getNumDirectories(); i < fullPath.getNumDirectories(); i++)
  304. {
  305. win32_createDirectory(parentPath.toWString());
  306. parentPath.append(fullPath[i]);
  307. }
  308. }
  309. void FileSystem::getChildren(const Path& dirPath, Vector<Path>::type& files, Vector<Path>::type& directories)
  310. {
  311. if (dirPath.isFile())
  312. return;
  313. WString findPath = dirPath.toWString();
  314. findPath.append(L"*");
  315. WIN32_FIND_DATAW findData;
  316. HANDLE fileHandle = FindFirstFileW(findPath.c_str(), &findData);
  317. bool lastFailed = false;
  318. WString tempName;
  319. do
  320. {
  321. if (lastFailed || fileHandle == INVALID_HANDLE_VALUE)
  322. {
  323. if (GetLastError() == ERROR_NO_MORE_FILES)
  324. break;
  325. else
  326. win32_handleError(GetLastError(), findPath);
  327. }
  328. else
  329. {
  330. tempName = findData.cFileName;
  331. if (tempName != L"." && tempName != L"..")
  332. {
  333. Path fullPath = dirPath;
  334. if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
  335. directories.push_back(fullPath.append(tempName));
  336. else
  337. files.push_back(fullPath.append(tempName));
  338. }
  339. }
  340. lastFailed = FindNextFileW(fileHandle, &findData) == FALSE;
  341. } while (true);
  342. }
  343. std::time_t FileSystem::getLastModifiedTime(const Path& fullPath)
  344. {
  345. return win32_getLastModifiedTime(fullPath.toWString().c_str());
  346. }
  347. Path FileSystem::getWorkingDirectoryPath()
  348. {
  349. return Path(win32_getCurrentDirectory());
  350. }
  351. }