CCFileUtils-win32.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 "tinydir/tinydir.h"
  27. #include <Shlobj.h>
  28. #include <cstdlib>
  29. #include <regex>
  30. #include <sstream>
  31. using namespace std;
  32. NS_CC_BEGIN
  33. #define CC_MAX_PATH 512
  34. // The root path of resources, the character encoding is UTF-8.
  35. // UTF-8 is the only encoding supported by cocos2d-x API.
  36. static std::string s_resourcePath = "";
  37. // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt
  38. static inline std::string convertPathFormatToUnixStyle(const std::string& path)
  39. {
  40. std::string ret = path;
  41. int len = ret.length();
  42. for (int i = 0; i < len; ++i)
  43. {
  44. if (ret[i] == '\\')
  45. {
  46. ret[i] = '/';
  47. }
  48. }
  49. return ret;
  50. }
  51. static void _checkPath()
  52. {
  53. if (s_resourcePath.empty())
  54. {
  55. WCHAR utf16Path[CC_MAX_PATH] = { 0 };
  56. GetModuleFileNameW(NULL, utf16Path, CC_MAX_PATH - 1);
  57. WCHAR *pUtf16ExePath = &(utf16Path[0]);
  58. // We need only directory part without exe
  59. WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\');
  60. char utf8ExeDir[CC_MAX_PATH] = { 0 };
  61. int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, pUtf16DirEnd-pUtf16ExePath+1, utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr);
  62. s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir);
  63. }
  64. }
  65. FileUtils* FileUtils::getInstance()
  66. {
  67. if (s_sharedFileUtils == nullptr)
  68. {
  69. s_sharedFileUtils = new FileUtilsWin32();
  70. if(!s_sharedFileUtils->init())
  71. {
  72. delete s_sharedFileUtils;
  73. s_sharedFileUtils = nullptr;
  74. CCLOG("ERROR: Could not init CCFileUtilsWin32");
  75. }
  76. }
  77. return s_sharedFileUtils;
  78. }
  79. FileUtilsWin32::FileUtilsWin32()
  80. {
  81. }
  82. bool FileUtilsWin32::init()
  83. {
  84. _checkPath();
  85. _defaultResRootPath = s_resourcePath;
  86. return FileUtils::init();
  87. }
  88. bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const
  89. {
  90. unsigned long fAttrib = GetFileAttributes(StringUtf8ToWideChar(dirPath).c_str());
  91. if (fAttrib != INVALID_FILE_ATTRIBUTES &&
  92. (fAttrib & FILE_ATTRIBUTE_DIRECTORY))
  93. {
  94. return true;
  95. }
  96. return false;
  97. }
  98. std::string FileUtilsWin32::getSuitableFOpen(const std::string& filenameUtf8) const
  99. {
  100. return UTF8StringToMultiByte(filenameUtf8);
  101. }
  102. long FileUtilsWin32::getFileSize(const std::string &filepath)
  103. {
  104. WIN32_FILE_ATTRIBUTE_DATA fad;
  105. if (!GetFileAttributesEx(StringUtf8ToWideChar(filepath).c_str(), GetFileExInfoStandard, &fad))
  106. {
  107. return 0; // error condition, could call GetLastError to find out more
  108. }
  109. LARGE_INTEGER size;
  110. size.HighPart = fad.nFileSizeHigh;
  111. size.LowPart = fad.nFileSizeLow;
  112. return (long)size.QuadPart;
  113. }
  114. bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
  115. {
  116. if (strFilePath.empty())
  117. {
  118. return false;
  119. }
  120. std::string strPath = strFilePath;
  121. if (!isAbsolutePath(strPath))
  122. { // Not absolute path, add the default root path at the beginning.
  123. strPath.insert(0, _defaultResRootPath);
  124. }
  125. DWORD attr = GetFileAttributesW(StringUtf8ToWideChar(strPath).c_str());
  126. if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
  127. return false; // not a file
  128. return true;
  129. }
  130. bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const
  131. {
  132. if ( (strPath.length() > 2
  133. && ( (strPath[0] >= 'a' && strPath[0] <= 'z') || (strPath[0] >= 'A' && strPath[0] <= 'Z') )
  134. && strPath[1] == ':') || (strPath[0] == '/' && strPath[1] == '/'))
  135. {
  136. return true;
  137. }
  138. return false;
  139. }
  140. FileUtils::Status FileUtilsWin32::getContents(const std::string& filename, ResizableBuffer* buffer)
  141. {
  142. if (filename.empty())
  143. return FileUtils::Status::NotExists;
  144. // read the file from hardware
  145. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
  146. HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
  147. if (fileHandle == INVALID_HANDLE_VALUE)
  148. return FileUtils::Status::OpenFailed;
  149. DWORD hi;
  150. auto size = ::GetFileSize(fileHandle, &hi);
  151. if (hi > 0)
  152. {
  153. ::CloseHandle(fileHandle);
  154. return FileUtils::Status::TooLarge;
  155. }
  156. // don't read file content if it is empty
  157. if (size == 0)
  158. {
  159. ::CloseHandle(fileHandle);
  160. return FileUtils::Status::OK;
  161. }
  162. buffer->resize(size);
  163. DWORD sizeRead = 0;
  164. BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr);
  165. ::CloseHandle(fileHandle);
  166. if (!successed) {
  167. CCLOG("Get data from file(%s) failed, error code is %s", filename.data(), std::to_string(::GetLastError()).data());
  168. buffer->resize(sizeRead);
  169. return FileUtils::Status::ReadFailed;
  170. }
  171. return FileUtils::Status::OK;
  172. }
  173. std::string FileUtilsWin32::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const
  174. {
  175. std::string unixFileName = convertPathFormatToUnixStyle(filename);
  176. std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory);
  177. std::string unixSearchPath = convertPathFormatToUnixStyle(searchPath);
  178. return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath);
  179. }
  180. std::string FileUtilsWin32::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) const
  181. {
  182. std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory);
  183. std::string unixFilename = convertPathFormatToUnixStyle(strFilename);
  184. return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename);
  185. }
  186. void FileUtilsWin32::listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const
  187. {
  188. std::string fullpath = fullPathForFilename(dirPath);
  189. if (isDirectoryExist(fullpath))
  190. {
  191. tinydir_dir dir;
  192. std::wstring fullpathstr = StringUtf8ToWideChar(fullpath);
  193. if (tinydir_open(&dir, &fullpathstr[0]) != -1)
  194. {
  195. while (dir.has_next)
  196. {
  197. tinydir_file file;
  198. if (tinydir_readfile(&dir, &file) == -1)
  199. {
  200. // Error getting file
  201. break;
  202. }
  203. std::string fileName = StringWideCharToUtf8(file.name);
  204. if (fileName != "." && fileName != "..")
  205. {
  206. std::string filepath = StringWideCharToUtf8(file.path);
  207. if (file.is_dir)
  208. {
  209. filepath.append("/");
  210. files->push_back(filepath);
  211. listFilesRecursively(filepath, files);
  212. }
  213. else
  214. {
  215. files->push_back(filepath);
  216. }
  217. }
  218. if (tinydir_next(&dir) == -1)
  219. {
  220. // Error getting next file
  221. break;
  222. }
  223. }
  224. }
  225. tinydir_close(&dir);
  226. }
  227. }
  228. std::vector<std::string> FileUtilsWin32::listFiles(const std::string& dirPath) const
  229. {
  230. std::string fullpath = fullPathForFilename(dirPath);
  231. std::vector<std::string> files;
  232. if (isDirectoryExist(fullpath))
  233. {
  234. tinydir_dir dir;
  235. std::wstring fullpathstr = StringUtf8ToWideChar(fullpath);
  236. if (tinydir_open(&dir, &fullpathstr[0]) != -1)
  237. {
  238. while (dir.has_next)
  239. {
  240. tinydir_file file;
  241. if (tinydir_readfile(&dir, &file) == -1)
  242. {
  243. // Error getting file
  244. break;
  245. }
  246. std::string filepath = StringWideCharToUtf8(file.path);
  247. if (file.is_dir)
  248. {
  249. filepath.append("/");
  250. }
  251. files.push_back(filepath);
  252. if (tinydir_next(&dir) == -1)
  253. {
  254. // Error getting next file
  255. break;
  256. }
  257. }
  258. }
  259. tinydir_close(&dir);
  260. }
  261. return files;
  262. }
  263. string FileUtilsWin32::getWritablePath() const
  264. {
  265. if (_writablePath.length())
  266. {
  267. return _writablePath;
  268. }
  269. // Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe
  270. WCHAR full_path[CC_MAX_PATH + 1] = { 0 };
  271. ::GetModuleFileName(nullptr, full_path, CC_MAX_PATH + 1);
  272. // Debug app uses executable directory; Non-debug app uses local app data directory
  273. //#ifndef _DEBUG
  274. // Get filename of executable only, e.g. MyGame.exe
  275. WCHAR *base_name = wcsrchr(full_path, '\\');
  276. wstring retPath;
  277. if(base_name)
  278. {
  279. WCHAR app_data_path[CC_MAX_PATH + 1];
  280. // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data
  281. if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
  282. {
  283. wstring ret(app_data_path);
  284. // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe
  285. ret += base_name;
  286. // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame
  287. ret = ret.substr(0, ret.rfind(L"."));
  288. ret += L"\\";
  289. // Create directory
  290. if (SUCCEEDED(SHCreateDirectoryEx(nullptr, ret.c_str(), nullptr)))
  291. {
  292. retPath = ret;
  293. }
  294. }
  295. }
  296. if (retPath.empty())
  297. //#endif // not defined _DEBUG
  298. {
  299. // If fetching of local app data directory fails, use the executable one
  300. retPath = full_path;
  301. // remove xxx.exe
  302. retPath = retPath.substr(0, retPath.rfind(L"\\") + 1);
  303. }
  304. return convertPathFormatToUnixStyle(StringWideCharToUtf8(retPath));
  305. }
  306. bool FileUtilsWin32::renameFile(const std::string &oldfullpath, const std::string& newfullpath)
  307. {
  308. CCASSERT(!oldfullpath.empty(), "Invalid path");
  309. CCASSERT(!newfullpath.empty(), "Invalid path");
  310. std::wstring _wNew = StringUtf8ToWideChar(newfullpath);
  311. std::wstring _wOld = StringUtf8ToWideChar(oldfullpath);
  312. if (FileUtils::getInstance()->isFileExist(newfullpath))
  313. {
  314. if (!DeleteFile(_wNew.c_str()))
  315. {
  316. CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.c_str(), GetLastError());
  317. }
  318. }
  319. if (MoveFile(_wOld.c_str(), _wNew.c_str()))
  320. {
  321. return true;
  322. }
  323. else
  324. {
  325. CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.c_str(), newfullpath.c_str(), GetLastError());
  326. return false;
  327. }
  328. }
  329. bool FileUtilsWin32::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
  330. {
  331. CCASSERT(!path.empty(), "Invalid path");
  332. std::string oldPath = path + oldname;
  333. std::string newPath = path + name;
  334. std::regex pat("\\/");
  335. std::string _old = std::regex_replace(oldPath, pat, "\\");
  336. std::string _new = std::regex_replace(newPath, pat, "\\");
  337. return renameFile(_old, _new);
  338. }
  339. bool FileUtilsWin32::createDirectory(const std::string& dirPath)
  340. {
  341. CCASSERT(!dirPath.empty(), "Invalid path");
  342. if (isDirectoryExist(dirPath))
  343. return true;
  344. std::wstring path = StringUtf8ToWideChar(dirPath);
  345. // Split the path
  346. size_t start = 0;
  347. size_t found = path.find_first_of(L"/\\", start);
  348. std::wstring subpath;
  349. std::vector<std::wstring> dirs;
  350. if (found != std::wstring::npos)
  351. {
  352. while (true)
  353. {
  354. subpath = path.substr(start, found - start + 1);
  355. if (!subpath.empty())
  356. dirs.push_back(subpath);
  357. start = found + 1;
  358. found = path.find_first_of(L"/\\", start);
  359. if (found == std::wstring::npos)
  360. {
  361. if (start < path.length())
  362. {
  363. dirs.push_back(path.substr(start));
  364. }
  365. break;
  366. }
  367. }
  368. }
  369. if ((GetFileAttributes(path.c_str())) == INVALID_FILE_ATTRIBUTES)
  370. {
  371. subpath = L"";
  372. for (unsigned int i = 0, size = dirs.size(); i < size; ++i)
  373. {
  374. subpath += dirs[i];
  375. std::string utf8Path = StringWideCharToUtf8(subpath);
  376. if (!isDirectoryExist(utf8Path))
  377. {
  378. BOOL ret = CreateDirectory(subpath.c_str(), NULL);
  379. if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
  380. {
  381. CCLOGERROR("Fail create directory %s !Error code is 0x%x", utf8Path.c_str(), GetLastError());
  382. return false;
  383. }
  384. }
  385. }
  386. }
  387. return true;
  388. }
  389. bool FileUtilsWin32::removeFile(const std::string &filepath)
  390. {
  391. std::regex pat("\\/");
  392. std::string win32path = std::regex_replace(filepath, pat, "\\");
  393. if (DeleteFile(StringUtf8ToWideChar(win32path).c_str()))
  394. {
  395. return true;
  396. }
  397. else
  398. {
  399. CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError());
  400. return false;
  401. }
  402. }
  403. bool FileUtilsWin32::removeDirectory(const std::string& dirPath)
  404. {
  405. std::wstring wpath = StringUtf8ToWideChar(dirPath);
  406. std::wstring files = wpath + L"*.*";
  407. WIN32_FIND_DATA wfd;
  408. HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
  409. bool ret = true;
  410. if (search != INVALID_HANDLE_VALUE)
  411. {
  412. BOOL find = true;
  413. while (find)
  414. {
  415. // Need check string . and .. for delete folders and files begin name.
  416. std::wstring fileName = wfd.cFileName;
  417. if (fileName != L"." && fileName != L"..")
  418. {
  419. std::wstring temp = wpath + wfd.cFileName;
  420. if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  421. {
  422. temp += '/';
  423. ret = ret && this->removeDirectory(StringWideCharToUtf8(temp));
  424. }
  425. else
  426. {
  427. SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
  428. ret = ret && DeleteFile(temp.c_str());
  429. }
  430. }
  431. find = FindNextFile(search, &wfd);
  432. }
  433. FindClose(search);
  434. }
  435. if (ret && RemoveDirectory(wpath.c_str()))
  436. {
  437. return true;
  438. }
  439. return false;
  440. }
  441. NS_CC_END
  442. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32