CCFileUtils-win32.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "platform/CCPlatformConfig.h"
  22. #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  23. #include "platform/win32/CCFileUtils-win32.h"
  24. #include "platform/win32/CCUtils-win32.h"
  25. #include "platform/CCCommon.h"
  26. #include <Shlobj.h>
  27. #include <cstdlib>
  28. #include <regex>
  29. #include <sstream>
  30. using namespace std;
  31. NS_CC_BEGIN
  32. #define CC_MAX_PATH 512
  33. // The root path of resources, the character encoding is UTF-8.
  34. // UTF-8 is the only encoding supported by cocos2d-x API.
  35. static std::string s_resourcePath = "";
  36. // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt
  37. static inline std::string convertPathFormatToUnixStyle(const std::string& path)
  38. {
  39. std::string ret = path;
  40. int len = ret.length();
  41. for (int i = 0; i < len; ++i)
  42. {
  43. if (ret[i] == '\\')
  44. {
  45. ret[i] = '/';
  46. }
  47. }
  48. return ret;
  49. }
  50. static void _checkPath()
  51. {
  52. if (s_resourcePath.empty())
  53. {
  54. WCHAR utf16Path[CC_MAX_PATH] = { 0 };
  55. GetModuleFileNameW(NULL, utf16Path, CC_MAX_PATH - 1);
  56. WCHAR *pUtf16ExePath = &(utf16Path[0]);
  57. // We need only directory part without exe
  58. WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\');
  59. char utf8ExeDir[CC_MAX_PATH] = { 0 };
  60. int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, pUtf16DirEnd-pUtf16ExePath+1, utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr);
  61. s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir);
  62. }
  63. }
  64. FileUtils* FileUtils::getInstance()
  65. {
  66. if (s_sharedFileUtils == nullptr)
  67. {
  68. s_sharedFileUtils = new FileUtilsWin32();
  69. if(!s_sharedFileUtils->init())
  70. {
  71. delete s_sharedFileUtils;
  72. s_sharedFileUtils = nullptr;
  73. CCLOG("ERROR: Could not init CCFileUtilsWin32");
  74. }
  75. }
  76. return s_sharedFileUtils;
  77. }
  78. FileUtilsWin32::FileUtilsWin32()
  79. {
  80. }
  81. bool FileUtilsWin32::init()
  82. {
  83. _checkPath();
  84. _defaultResRootPath = s_resourcePath;
  85. return FileUtils::init();
  86. }
  87. bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const
  88. {
  89. unsigned long fAttrib = GetFileAttributes(StringUtf8ToWideChar(dirPath).c_str());
  90. if (fAttrib != INVALID_FILE_ATTRIBUTES &&
  91. (fAttrib & FILE_ATTRIBUTE_DIRECTORY))
  92. {
  93. return true;
  94. }
  95. return false;
  96. }
  97. std::string FileUtilsWin32::getSuitableFOpen(const std::string& filenameUtf8) const
  98. {
  99. return UTF8StringToMultiByte(filenameUtf8);
  100. }
  101. long FileUtilsWin32::getFileSize(const std::string &filepath)
  102. {
  103. WIN32_FILE_ATTRIBUTE_DATA fad;
  104. if (!GetFileAttributesEx(StringUtf8ToWideChar(filepath).c_str(), GetFileExInfoStandard, &fad))
  105. {
  106. return 0; // error condition, could call GetLastError to find out more
  107. }
  108. LARGE_INTEGER size;
  109. size.HighPart = fad.nFileSizeHigh;
  110. size.LowPart = fad.nFileSizeLow;
  111. return (long)size.QuadPart;
  112. }
  113. bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
  114. {
  115. if (strFilePath.empty())
  116. {
  117. return false;
  118. }
  119. std::string strPath = strFilePath;
  120. if (!isAbsolutePath(strPath))
  121. { // Not absolute path, add the default root path at the beginning.
  122. strPath.insert(0, _defaultResRootPath);
  123. }
  124. DWORD attr = GetFileAttributesW(StringUtf8ToWideChar(strPath).c_str());
  125. if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
  126. return false; // not a file
  127. return true;
  128. }
  129. bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const
  130. {
  131. if ( (strPath.length() > 2
  132. && ( (strPath[0] >= 'a' && strPath[0] <= 'z') || (strPath[0] >= 'A' && strPath[0] <= 'Z') )
  133. && strPath[1] == ':') || (strPath[0] == '/' && strPath[1] == '/'))
  134. {
  135. return true;
  136. }
  137. return false;
  138. }
  139. FileUtils::Status FileUtilsWin32::getContents(const std::string& filename, ResizableBuffer* buffer)
  140. {
  141. if (filename.empty())
  142. return FileUtils::Status::NotExists;
  143. // read the file from hardware
  144. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
  145. HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
  146. if (fileHandle == INVALID_HANDLE_VALUE)
  147. return FileUtils::Status::OpenFailed;
  148. DWORD hi;
  149. auto size = ::GetFileSize(fileHandle, &hi);
  150. if (hi > 0)
  151. {
  152. ::CloseHandle(fileHandle);
  153. return FileUtils::Status::TooLarge;
  154. }
  155. // don't read file content if it is empty
  156. if (size == 0)
  157. {
  158. ::CloseHandle(fileHandle);
  159. return FileUtils::Status::OK;
  160. }
  161. buffer->resize(size);
  162. DWORD sizeRead = 0;
  163. BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr);
  164. ::CloseHandle(fileHandle);
  165. if (!successed) {
  166. CCLOG("Get data from file(%s) failed, error code is %s", filename.data(), std::to_string(::GetLastError()).data());
  167. buffer->resize(sizeRead);
  168. return FileUtils::Status::ReadFailed;
  169. }
  170. return FileUtils::Status::OK;
  171. }
  172. std::string FileUtilsWin32::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const
  173. {
  174. std::string unixFileName = convertPathFormatToUnixStyle(filename);
  175. std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory);
  176. std::string unixSearchPath = convertPathFormatToUnixStyle(searchPath);
  177. return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath);
  178. }
  179. std::string FileUtilsWin32::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) const
  180. {
  181. std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory);
  182. std::string unixFilename = convertPathFormatToUnixStyle(strFilename);
  183. return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename);
  184. }
  185. string FileUtilsWin32::getWritablePath() const
  186. {
  187. if (_writablePath.length())
  188. {
  189. return _writablePath;
  190. }
  191. // Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe
  192. WCHAR full_path[CC_MAX_PATH + 1] = { 0 };
  193. ::GetModuleFileName(nullptr, full_path, CC_MAX_PATH + 1);
  194. // Debug app uses executable directory; Non-debug app uses local app data directory
  195. //#ifndef _DEBUG
  196. // Get filename of executable only, e.g. MyGame.exe
  197. WCHAR *base_name = wcsrchr(full_path, '\\');
  198. wstring retPath;
  199. if(base_name)
  200. {
  201. WCHAR app_data_path[CC_MAX_PATH + 1];
  202. // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data
  203. if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
  204. {
  205. wstring ret(app_data_path);
  206. // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe
  207. ret += base_name;
  208. // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame
  209. ret = ret.substr(0, ret.rfind(L"."));
  210. ret += L"\\";
  211. // Create directory
  212. if (SUCCEEDED(SHCreateDirectoryEx(nullptr, ret.c_str(), nullptr)))
  213. {
  214. retPath = ret;
  215. }
  216. }
  217. }
  218. if (retPath.empty())
  219. //#endif // not defined _DEBUG
  220. {
  221. // If fetching of local app data directory fails, use the executable one
  222. retPath = full_path;
  223. // remove xxx.exe
  224. retPath = retPath.substr(0, retPath.rfind(L"\\") + 1);
  225. }
  226. return convertPathFormatToUnixStyle(StringWideCharToUtf8(retPath));
  227. }
  228. bool FileUtilsWin32::renameFile(const std::string &oldfullpath, const std::string& newfullpath)
  229. {
  230. CCASSERT(!oldfullpath.empty(), "Invalid path");
  231. CCASSERT(!newfullpath.empty(), "Invalid path");
  232. std::wstring _wNew = StringUtf8ToWideChar(newfullpath);
  233. std::wstring _wOld = StringUtf8ToWideChar(oldfullpath);
  234. if (FileUtils::getInstance()->isFileExist(newfullpath))
  235. {
  236. if (!DeleteFile(_wNew.c_str()))
  237. {
  238. CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.c_str(), GetLastError());
  239. }
  240. }
  241. if (MoveFile(_wOld.c_str(), _wNew.c_str()))
  242. {
  243. return true;
  244. }
  245. else
  246. {
  247. CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.c_str(), newfullpath.c_str(), GetLastError());
  248. return false;
  249. }
  250. }
  251. bool FileUtilsWin32::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
  252. {
  253. CCASSERT(!path.empty(), "Invalid path");
  254. std::string oldPath = path + oldname;
  255. std::string newPath = path + name;
  256. std::regex pat("\\/");
  257. std::string _old = std::regex_replace(oldPath, pat, "\\");
  258. std::string _new = std::regex_replace(newPath, pat, "\\");
  259. return renameFile(_old, _new);
  260. }
  261. bool FileUtilsWin32::createDirectory(const std::string& dirPath)
  262. {
  263. CCASSERT(!dirPath.empty(), "Invalid path");
  264. if (isDirectoryExist(dirPath))
  265. return true;
  266. std::wstring path = StringUtf8ToWideChar(dirPath);
  267. // Split the path
  268. size_t start = 0;
  269. size_t found = path.find_first_of(L"/\\", start);
  270. std::wstring subpath;
  271. std::vector<std::wstring> dirs;
  272. if (found != std::wstring::npos)
  273. {
  274. while (true)
  275. {
  276. subpath = path.substr(start, found - start + 1);
  277. if (!subpath.empty())
  278. dirs.push_back(subpath);
  279. start = found + 1;
  280. found = path.find_first_of(L"/\\", start);
  281. if (found == std::wstring::npos)
  282. {
  283. if (start < path.length())
  284. {
  285. dirs.push_back(path.substr(start));
  286. }
  287. break;
  288. }
  289. }
  290. }
  291. if ((GetFileAttributes(path.c_str())) == INVALID_FILE_ATTRIBUTES)
  292. {
  293. subpath = L"";
  294. for (unsigned int i = 0, size = dirs.size(); i < size; ++i)
  295. {
  296. subpath += dirs[i];
  297. std::string utf8Path = StringWideCharToUtf8(subpath);
  298. if (!isDirectoryExist(utf8Path))
  299. {
  300. BOOL ret = CreateDirectory(subpath.c_str(), NULL);
  301. if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
  302. {
  303. CCLOGERROR("Fail create directory %s !Error code is 0x%x", utf8Path.c_str(), GetLastError());
  304. return false;
  305. }
  306. }
  307. }
  308. }
  309. return true;
  310. }
  311. bool FileUtilsWin32::removeFile(const std::string &filepath)
  312. {
  313. std::regex pat("\\/");
  314. std::string win32path = std::regex_replace(filepath, pat, "\\");
  315. if (DeleteFile(StringUtf8ToWideChar(win32path).c_str()))
  316. {
  317. return true;
  318. }
  319. else
  320. {
  321. CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError());
  322. return false;
  323. }
  324. }
  325. bool FileUtilsWin32::removeDirectory(const std::string& dirPath)
  326. {
  327. std::wstring wpath = StringUtf8ToWideChar(dirPath);
  328. std::wstring files = wpath + L"*.*";
  329. WIN32_FIND_DATA wfd;
  330. HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
  331. bool ret = true;
  332. if (search != INVALID_HANDLE_VALUE)
  333. {
  334. BOOL find = true;
  335. while (find)
  336. {
  337. // Need check string . and .. for delete folders and files begin name.
  338. std::wstring fileName = wfd.cFileName;
  339. if (fileName != L"." && fileName != L"..")
  340. {
  341. std::wstring temp = wpath + wfd.cFileName;
  342. if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  343. {
  344. temp += '/';
  345. ret = ret && this->removeDirectory(StringWideCharToUtf8(temp));
  346. }
  347. else
  348. {
  349. SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
  350. ret = ret && DeleteFile(temp.c_str());
  351. }
  352. }
  353. find = FindNextFile(search, &wfd);
  354. }
  355. FindClose(search);
  356. }
  357. if (ret && RemoveDirectory(wpath.c_str()))
  358. {
  359. return true;
  360. }
  361. return false;
  362. }
  363. NS_CC_END
  364. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32