CCFileUtils.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. /****************************************************************************
  2. Copyright (c) 2010-2013 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/CCFileUtils.h"
  22. #include <stack>
  23. #include "base/CCData.h"
  24. #include "base/ccMacros.h"
  25. #include "base/CCDirector.h"
  26. #include "platform/CCSAXParser.h"
  27. //#include "base/ccUtils.h"
  28. #include "tinyxml2/tinyxml2.h"
  29. #include "tinydir/tinydir.h"
  30. #ifdef MINIZIP_FROM_SYSTEM
  31. #include <minizip/unzip.h>
  32. #else // from our embedded sources
  33. #include "unzip.h"
  34. #endif
  35. #include <sys/stat.h>
  36. NS_CC_BEGIN
  37. // Implement DictMaker
  38. #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
  39. typedef enum
  40. {
  41. SAX_NONE = 0,
  42. SAX_KEY,
  43. SAX_DICT,
  44. SAX_INT,
  45. SAX_REAL,
  46. SAX_STRING,
  47. SAX_ARRAY
  48. }SAXState;
  49. typedef enum
  50. {
  51. SAX_RESULT_NONE = 0,
  52. SAX_RESULT_DICT,
  53. SAX_RESULT_ARRAY
  54. }SAXResult;
  55. class DictMaker : public SAXDelegator
  56. {
  57. public:
  58. SAXResult _resultType;
  59. ValueMap _rootDict;
  60. ValueVector _rootArray;
  61. std::string _curKey; ///< parsed key
  62. std::string _curValue; // parsed value
  63. SAXState _state;
  64. ValueMap* _curDict;
  65. ValueVector* _curArray;
  66. std::stack<ValueMap*> _dictStack;
  67. std::stack<ValueVector*> _arrayStack;
  68. std::stack<SAXState> _stateStack;
  69. public:
  70. DictMaker()
  71. : _resultType(SAX_RESULT_NONE)
  72. {
  73. }
  74. ~DictMaker()
  75. {
  76. }
  77. ValueMap dictionaryWithContentsOfFile(const std::string& fileName)
  78. {
  79. _resultType = SAX_RESULT_DICT;
  80. SAXParser parser;
  81. CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
  82. parser.setDelegator(this);
  83. parser.parse(fileName);
  84. return _rootDict;
  85. }
  86. ValueMap dictionaryWithDataOfFile(const char* filedata, int filesize)
  87. {
  88. _resultType = SAX_RESULT_DICT;
  89. SAXParser parser;
  90. CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
  91. parser.setDelegator(this);
  92. parser.parse(filedata, filesize);
  93. return _rootDict;
  94. }
  95. ValueVector arrayWithContentsOfFile(const std::string& fileName)
  96. {
  97. _resultType = SAX_RESULT_ARRAY;
  98. SAXParser parser;
  99. CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
  100. parser.setDelegator(this);
  101. parser.parse(fileName);
  102. return _rootArray;
  103. }
  104. void startElement(void *ctx, const char *name, const char **atts)
  105. {
  106. const std::string sName(name);
  107. if( sName == "dict" )
  108. {
  109. if(_resultType == SAX_RESULT_DICT && _rootDict.empty())
  110. {
  111. _curDict = &_rootDict;
  112. }
  113. _state = SAX_DICT;
  114. SAXState preState = SAX_NONE;
  115. if (! _stateStack.empty())
  116. {
  117. preState = _stateStack.top();
  118. }
  119. if (SAX_ARRAY == preState)
  120. {
  121. // add a new dictionary into the array
  122. _curArray->push_back(Value(ValueMap()));
  123. _curDict = &(_curArray->rbegin())->asValueMap();
  124. }
  125. else if (SAX_DICT == preState)
  126. {
  127. // add a new dictionary into the pre dictionary
  128. CCASSERT(! _dictStack.empty(), "The state is wrong!");
  129. ValueMap* preDict = _dictStack.top();
  130. (*preDict)[_curKey] = Value(ValueMap());
  131. _curDict = &(*preDict)[_curKey].asValueMap();
  132. }
  133. // record the dict state
  134. _stateStack.push(_state);
  135. _dictStack.push(_curDict);
  136. }
  137. else if(sName == "key")
  138. {
  139. _state = SAX_KEY;
  140. }
  141. else if(sName == "integer")
  142. {
  143. _state = SAX_INT;
  144. }
  145. else if(sName == "real")
  146. {
  147. _state = SAX_REAL;
  148. }
  149. else if(sName == "string")
  150. {
  151. _state = SAX_STRING;
  152. }
  153. else if (sName == "array")
  154. {
  155. _state = SAX_ARRAY;
  156. if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty())
  157. {
  158. _curArray = &_rootArray;
  159. }
  160. SAXState preState = SAX_NONE;
  161. if (! _stateStack.empty())
  162. {
  163. preState = _stateStack.top();
  164. }
  165. if (preState == SAX_DICT)
  166. {
  167. (*_curDict)[_curKey] = Value(ValueVector());
  168. _curArray = &(*_curDict)[_curKey].asValueVector();
  169. }
  170. else if (preState == SAX_ARRAY)
  171. {
  172. CCASSERT(! _arrayStack.empty(), "The state is wrong!");
  173. ValueVector* preArray = _arrayStack.top();
  174. preArray->push_back(Value(ValueVector()));
  175. _curArray = &(_curArray->rbegin())->asValueVector();
  176. }
  177. // record the array state
  178. _stateStack.push(_state);
  179. _arrayStack.push(_curArray);
  180. }
  181. else
  182. {
  183. _state = SAX_NONE;
  184. }
  185. }
  186. void endElement(void *ctx, const char *name)
  187. {
  188. SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top();
  189. const std::string sName((char*)name);
  190. if( sName == "dict" )
  191. {
  192. _stateStack.pop();
  193. _dictStack.pop();
  194. if ( !_dictStack.empty())
  195. {
  196. _curDict = _dictStack.top();
  197. }
  198. }
  199. else if (sName == "array")
  200. {
  201. _stateStack.pop();
  202. _arrayStack.pop();
  203. if (! _arrayStack.empty())
  204. {
  205. _curArray = _arrayStack.top();
  206. }
  207. }
  208. else if (sName == "true")
  209. {
  210. if (SAX_ARRAY == curState)
  211. {
  212. _curArray->push_back(Value(true));
  213. }
  214. else if (SAX_DICT == curState)
  215. {
  216. (*_curDict)[_curKey] = Value(true);
  217. }
  218. }
  219. else if (sName == "false")
  220. {
  221. if (SAX_ARRAY == curState)
  222. {
  223. _curArray->push_back(Value(false));
  224. }
  225. else if (SAX_DICT == curState)
  226. {
  227. (*_curDict)[_curKey] = Value(false);
  228. }
  229. }
  230. else if (sName == "string" || sName == "integer" || sName == "real")
  231. {
  232. if (SAX_ARRAY == curState)
  233. {
  234. if (sName == "string")
  235. _curArray->push_back(Value(_curValue));
  236. else if (sName == "integer")
  237. _curArray->push_back(Value(atoi(_curValue.c_str())));
  238. else
  239. _curArray->push_back(Value(std::atof(_curValue.c_str())));
  240. }
  241. else if (SAX_DICT == curState)
  242. {
  243. if (sName == "string")
  244. (*_curDict)[_curKey] = Value(_curValue);
  245. else if (sName == "integer")
  246. (*_curDict)[_curKey] = Value(atoi(_curValue.c_str()));
  247. else
  248. (*_curDict)[_curKey] = Value(std::atof(_curValue.c_str()));
  249. }
  250. _curValue.clear();
  251. }
  252. _state = SAX_NONE;
  253. }
  254. void textHandler(void *ctx, const char *ch, size_t len) override
  255. {
  256. if (_state == SAX_NONE)
  257. {
  258. return;
  259. }
  260. SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top();
  261. const std::string text = std::string((char*)ch,len);
  262. switch(_state)
  263. {
  264. case SAX_KEY:
  265. _curKey = text;
  266. break;
  267. case SAX_INT:
  268. case SAX_REAL:
  269. case SAX_STRING:
  270. {
  271. if (curState == SAX_DICT)
  272. {
  273. CCASSERT(!_curKey.empty(), "key not found : <integer/real>");
  274. }
  275. _curValue.append(text);
  276. }
  277. break;
  278. default:
  279. break;
  280. }
  281. }
  282. };
  283. ValueMap FileUtils::getValueMapFromFile(const std::string& filename)
  284. {
  285. const std::string fullPath = fullPathForFilename(filename);
  286. DictMaker tMaker;
  287. return tMaker.dictionaryWithContentsOfFile(fullPath);
  288. }
  289. ValueMap FileUtils::getValueMapFromData(const char* filedata, int filesize)
  290. {
  291. DictMaker tMaker;
  292. return tMaker.dictionaryWithDataOfFile(filedata, filesize);
  293. }
  294. ValueVector FileUtils::getValueVectorFromFile(const std::string& filename)
  295. {
  296. const std::string fullPath = fullPathForFilename(filename);
  297. DictMaker tMaker;
  298. return tMaker.arrayWithContentsOfFile(fullPath);
  299. }
  300. /*
  301. * forward statement
  302. */
  303. static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, tinyxml2::XMLDocument *doc);
  304. static tinyxml2::XMLElement* generateElementForDict(const ValueMap& dict, tinyxml2::XMLDocument *doc);
  305. /*
  306. * Use tinyxml2 to write plist files
  307. */
  308. bool FileUtils::writeToFile(const ValueMap& dict, const std::string &fullPath)
  309. {
  310. return writeValueMapToFile(dict, fullPath);
  311. }
  312. bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath)
  313. {
  314. tinyxml2::XMLDocument *doc = new (std::nothrow)tinyxml2::XMLDocument();
  315. if (nullptr == doc)
  316. return false;
  317. tinyxml2::XMLDeclaration *declaration = doc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
  318. if (nullptr == declaration)
  319. {
  320. delete doc;
  321. return false;
  322. }
  323. doc->LinkEndChild(declaration);
  324. tinyxml2::XMLElement *docType = doc->NewElement("!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  325. doc->LinkEndChild(docType);
  326. tinyxml2::XMLElement *rootEle = doc->NewElement("plist");
  327. rootEle->SetAttribute("version", "1.0");
  328. if (nullptr == rootEle)
  329. {
  330. delete doc;
  331. return false;
  332. }
  333. doc->LinkEndChild(rootEle);
  334. tinyxml2::XMLElement *innerDict = generateElementForDict(dict, doc);
  335. if (nullptr == innerDict)
  336. {
  337. delete doc;
  338. return false;
  339. }
  340. rootEle->LinkEndChild(innerDict);
  341. bool ret = tinyxml2::XML_SUCCESS == doc->SaveFile(getSuitableFOpen(fullPath).c_str());
  342. delete doc;
  343. return ret;
  344. }
  345. bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath)
  346. {
  347. tinyxml2::XMLDocument *doc = new (std::nothrow)tinyxml2::XMLDocument();
  348. if (nullptr == doc)
  349. return false;
  350. tinyxml2::XMLDeclaration *declaration = doc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
  351. if (nullptr == declaration)
  352. {
  353. delete doc;
  354. return false;
  355. }
  356. doc->LinkEndChild(declaration);
  357. tinyxml2::XMLElement *docType = doc->NewElement("!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"");
  358. doc->LinkEndChild(docType);
  359. tinyxml2::XMLElement *rootEle = doc->NewElement("plist");
  360. rootEle->SetAttribute("version", "1.0");
  361. if (nullptr == rootEle)
  362. {
  363. delete doc;
  364. return false;
  365. }
  366. doc->LinkEndChild(rootEle);
  367. tinyxml2::XMLElement *innerDict = generateElementForArray(vecData, doc);
  368. if (nullptr == innerDict)
  369. {
  370. delete doc;
  371. return false;
  372. }
  373. rootEle->LinkEndChild(innerDict);
  374. bool ret = tinyxml2::XML_SUCCESS == doc->SaveFile(getSuitableFOpen(fullPath).c_str());
  375. delete doc;
  376. return ret;
  377. }
  378. /*
  379. * Generate tinyxml2::XMLElement for Object through a tinyxml2::XMLDocument
  380. */
  381. static tinyxml2::XMLElement* generateElementForObject(const Value& value, tinyxml2::XMLDocument *doc)
  382. {
  383. // object is String
  384. if (value.getType() == Value::Type::STRING)
  385. {
  386. tinyxml2::XMLElement* node = doc->NewElement("string");
  387. tinyxml2::XMLText* content = doc->NewText(value.asString().c_str());
  388. node->LinkEndChild(content);
  389. return node;
  390. }
  391. // object is integer
  392. if (value.getType() == Value::Type::INTEGER)
  393. {
  394. tinyxml2::XMLElement* node = doc->NewElement("integer");
  395. tinyxml2::XMLText* content = doc->NewText(value.asString().c_str());
  396. node->LinkEndChild(content);
  397. return node;
  398. }
  399. // object is real
  400. if (value.getType() == Value::Type::FLOAT || value.getType() == Value::Type::DOUBLE)
  401. {
  402. tinyxml2::XMLElement* node = doc->NewElement("real");
  403. tinyxml2::XMLText* content = doc->NewText(value.asString().c_str());
  404. node->LinkEndChild(content);
  405. return node;
  406. }
  407. //object is bool
  408. if (value.getType() == Value::Type::BOOLEAN) {
  409. tinyxml2::XMLElement* node = doc->NewElement(value.asString().c_str());
  410. return node;
  411. }
  412. // object is Array
  413. if (value.getType() == Value::Type::VECTOR)
  414. return generateElementForArray(value.asValueVector(), doc);
  415. // object is Dictionary
  416. if (value.getType() == Value::Type::MAP)
  417. return generateElementForDict(value.asValueMap(), doc);
  418. CCLOG("This type cannot appear in property list");
  419. return nullptr;
  420. }
  421. /*
  422. * Generate tinyxml2::XMLElement for Dictionary through a tinyxml2::XMLDocument
  423. */
  424. static tinyxml2::XMLElement* generateElementForDict(const ValueMap& dict, tinyxml2::XMLDocument *doc)
  425. {
  426. tinyxml2::XMLElement* rootNode = doc->NewElement("dict");
  427. for (const auto &iter : dict)
  428. {
  429. tinyxml2::XMLElement* tmpNode = doc->NewElement("key");
  430. rootNode->LinkEndChild(tmpNode);
  431. tinyxml2::XMLText* content = doc->NewText(iter.first.c_str());
  432. tmpNode->LinkEndChild(content);
  433. tinyxml2::XMLElement *element = generateElementForObject(iter.second, doc);
  434. if (element)
  435. rootNode->LinkEndChild(element);
  436. }
  437. return rootNode;
  438. }
  439. /*
  440. * Generate tinyxml2::XMLElement for Array through a tinyxml2::XMLDocument
  441. */
  442. static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, tinyxml2::XMLDocument *pDoc)
  443. {
  444. tinyxml2::XMLElement* rootNode = pDoc->NewElement("array");
  445. for(const auto &value : array) {
  446. tinyxml2::XMLElement *element = generateElementForObject(value, pDoc);
  447. if (element)
  448. rootNode->LinkEndChild(element);
  449. }
  450. return rootNode;
  451. }
  452. #else
  453. /* The subclass FileUtilsApple should override these two method. */
  454. ValueMap FileUtils::getValueMapFromFile(const std::string& /*filename*/) {return ValueMap();}
  455. ValueMap FileUtils::getValueMapFromData(const char* /*filedata*/, int /*filesize*/) {return ValueMap();}
  456. ValueVector FileUtils::getValueVectorFromFile(const std::string& /*filename*/) {return ValueVector();}
  457. bool FileUtils::writeToFile(const ValueMap& /*dict*/, const std::string &/*fullPath*/) {return false;}
  458. #endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */
  459. // Implement FileUtils
  460. FileUtils* FileUtils::s_sharedFileUtils = nullptr;
  461. void FileUtils::destroyInstance()
  462. {
  463. CC_SAFE_DELETE(s_sharedFileUtils);
  464. }
  465. void FileUtils::setDelegate(FileUtils *delegate)
  466. {
  467. if (s_sharedFileUtils)
  468. delete s_sharedFileUtils;
  469. s_sharedFileUtils = delegate;
  470. }
  471. FileUtils::FileUtils()
  472. : _writablePath("")
  473. {
  474. }
  475. FileUtils::~FileUtils()
  476. {
  477. }
  478. bool FileUtils::writeStringToFile(const std::string& dataStr, const std::string& fullPath)
  479. {
  480. Data data;
  481. data.fastSet((unsigned char*)dataStr.c_str(), dataStr.size());
  482. bool rv = writeDataToFile(data, fullPath);
  483. data.fastSet(nullptr, 0);
  484. return rv;
  485. }
  486. void FileUtils::writeStringToFile(std::string dataStr, const std::string& fullPath, std::function<void(bool)> callback)
  487. {
  488. performOperationOffthread([fullPath](const std::string& dataStrIn) -> bool {
  489. return FileUtils::getInstance()->writeStringToFile(dataStrIn, fullPath);
  490. }, std::move(callback),std::move(dataStr));
  491. }
  492. bool FileUtils::writeDataToFile(const Data& data, const std::string& fullPath)
  493. {
  494. size_t size = 0;
  495. const char* mode = "wb";
  496. CCASSERT(!fullPath.empty() && data.getSize() != 0, "Invalid parameters.");
  497. auto fileutils = FileUtils::getInstance();
  498. do
  499. {
  500. // Read the file from hardware
  501. FILE *fp = fopen(fileutils->getSuitableFOpen(fullPath).c_str(), mode);
  502. CC_BREAK_IF(!fp);
  503. size = data.getSize();
  504. fwrite(data.getBytes(), size, 1, fp);
  505. fclose(fp);
  506. return true;
  507. } while (0);
  508. return false;
  509. }
  510. void FileUtils::writeDataToFile(Data data, const std::string& fullPath, std::function<void(bool)> callback)
  511. {
  512. performOperationOffthread([fullPath](const Data& dataIn) -> bool {
  513. return FileUtils::getInstance()->writeDataToFile(dataIn, fullPath);
  514. }, std::move(callback), std::move(data));
  515. }
  516. bool FileUtils::init()
  517. {
  518. _searchPathArray.push_back(_defaultResRootPath);
  519. _searchResolutionsOrderArray.push_back("");
  520. return true;
  521. }
  522. void FileUtils::purgeCachedEntries()
  523. {
  524. _fullPathCache.clear();
  525. }
  526. std::string FileUtils::getStringFromFile(const std::string& filename)
  527. {
  528. std::string s;
  529. getContents(filename, &s);
  530. return s;
  531. }
  532. void FileUtils::getStringFromFile(const std::string &path, std::function<void (std::string)> callback)
  533. {
  534. // Get the full path on the main thread, to avoid the issue that FileUtil's is not
  535. // thread safe, and accessing the fullPath cache and searching the search paths is not thread safe
  536. auto fullPath = fullPathForFilename(path);
  537. performOperationOffthread([fullPath]() -> std::string {
  538. return FileUtils::getInstance()->getStringFromFile(fullPath);
  539. }, std::move(callback));
  540. }
  541. Data FileUtils::getDataFromFile(const std::string& filename)
  542. {
  543. Data d;
  544. getContents(filename, &d);
  545. return d;
  546. }
  547. void FileUtils::getDataFromFile(const std::string& filename, std::function<void(Data)> callback)
  548. {
  549. auto fullPath = fullPathForFilename(filename);
  550. performOperationOffthread([fullPath]() -> Data {
  551. return FileUtils::getInstance()->getDataFromFile(fullPath);
  552. }, std::move(callback));
  553. }
  554. FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableBuffer* buffer)
  555. {
  556. if (filename.empty())
  557. return Status::NotExists;
  558. auto fs = FileUtils::getInstance();
  559. std::string fullPath = fs->fullPathForFilename(filename);
  560. if (fullPath.empty())
  561. return Status::NotExists;
  562. FILE *fp = fopen(fs->getSuitableFOpen(fullPath).c_str(), "rb");
  563. if (!fp)
  564. return Status::OpenFailed;
  565. #if defined(_MSC_VER)
  566. auto descriptor = _fileno(fp);
  567. #else
  568. auto descriptor = fileno(fp);
  569. #endif
  570. struct stat statBuf;
  571. if (fstat(descriptor, &statBuf) == -1) {
  572. fclose(fp);
  573. return Status::ReadFailed;
  574. }
  575. size_t size = statBuf.st_size;
  576. buffer->resize(size);
  577. size_t readsize = fread(buffer->buffer(), 1, size, fp);
  578. fclose(fp);
  579. if (readsize < size) {
  580. buffer->resize(readsize);
  581. return Status::ReadFailed;
  582. }
  583. return Status::OK;
  584. }
  585. unsigned char* FileUtils::getFileData(const std::string& filename, const char* mode, ssize_t *size)
  586. {
  587. CCASSERT(!filename.empty() && size != nullptr && mode != nullptr, "Invalid parameters.");
  588. (void)(mode); // mode is unused, as we do not support text mode any more...
  589. Data d;
  590. if (getContents(filename, &d) != Status::OK) {
  591. *size = 0;
  592. return nullptr;
  593. }
  594. return d.takeBuffer(size);
  595. }
  596. unsigned char* FileUtils::getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size)
  597. {
  598. unsigned char * buffer = nullptr;
  599. unzFile file = nullptr;
  600. *size = 0;
  601. do
  602. {
  603. CC_BREAK_IF(zipFilePath.empty());
  604. file = unzOpen(FileUtils::getInstance()->getSuitableFOpen(zipFilePath).c_str());
  605. CC_BREAK_IF(!file);
  606. // FIXME: Other platforms should use upstream minizip like mingw-w64
  607. #ifdef MINIZIP_FROM_SYSTEM
  608. int ret = unzLocateFile(file, filename.c_str(), NULL);
  609. #else
  610. int ret = unzLocateFile(file, filename.c_str(), 1);
  611. #endif
  612. CC_BREAK_IF(UNZ_OK != ret);
  613. char filePathA[260];
  614. unz_file_info fileInfo;
  615. ret = unzGetCurrentFileInfo(file, &fileInfo, filePathA, sizeof(filePathA), nullptr, 0, nullptr, 0);
  616. CC_BREAK_IF(UNZ_OK != ret);
  617. ret = unzOpenCurrentFile(file);
  618. CC_BREAK_IF(UNZ_OK != ret);
  619. buffer = (unsigned char*)malloc(fileInfo.uncompressed_size);
  620. int CC_UNUSED readedSize = unzReadCurrentFile(file, buffer, static_cast<unsigned>(fileInfo.uncompressed_size));
  621. CCASSERT(readedSize == 0 || readedSize == (int)fileInfo.uncompressed_size, "the file size is wrong");
  622. *size = fileInfo.uncompressed_size;
  623. unzCloseCurrentFile(file);
  624. } while (0);
  625. if (file)
  626. {
  627. unzClose(file);
  628. }
  629. return buffer;
  630. }
  631. void FileUtils::writeValueMapToFile(ValueMap dict, const std::string& fullPath, std::function<void(bool)> callback)
  632. {
  633. performOperationOffthread([fullPath](const ValueMap& dictIn) -> bool {
  634. return FileUtils::getInstance()->writeValueMapToFile(dictIn, fullPath);
  635. }, std::move(callback), std::move(dict));
  636. }
  637. void FileUtils::writeValueVectorToFile(ValueVector vecData, const std::string& fullPath, std::function<void(bool)> callback)
  638. {
  639. performOperationOffthread([fullPath] (const ValueVector& vecDataIn) -> bool {
  640. return FileUtils::getInstance()->writeValueVectorToFile(vecDataIn, fullPath);
  641. }, std::move(callback), std::move(vecData));
  642. }
  643. std::string FileUtils::getNewFilename(const std::string &filename) const
  644. {
  645. std::string newFileName;
  646. // in Lookup Filename dictionary ?
  647. auto iter = _filenameLookupDict.find(filename);
  648. if (iter == _filenameLookupDict.end())
  649. {
  650. newFileName = filename;
  651. }
  652. else
  653. {
  654. newFileName = iter->second.asString();
  655. }
  656. return newFileName;
  657. }
  658. std::string FileUtils::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const
  659. {
  660. std::string file = filename;
  661. std::string file_path = "";
  662. size_t pos = filename.find_last_of("/");
  663. if (pos != std::string::npos)
  664. {
  665. file_path = filename.substr(0, pos+1);
  666. file = filename.substr(pos+1);
  667. }
  668. // searchPath + file_path + resourceDirectory
  669. std::string path = searchPath;
  670. path += file_path;
  671. path += resolutionDirectory;
  672. path = getFullPathForDirectoryAndFilename(path, file);
  673. return path;
  674. }
  675. std::string FileUtils::fullPathForFilename(const std::string &filename) const
  676. {
  677. if (filename.empty())
  678. {
  679. return "";
  680. }
  681. if (isAbsolutePath(filename))
  682. {
  683. return filename;
  684. }
  685. // Already Cached ?
  686. auto cacheIter = _fullPathCache.find(filename);
  687. if(cacheIter != _fullPathCache.end())
  688. {
  689. return cacheIter->second;
  690. }
  691. // Get the new file name.
  692. const std::string newFilename( getNewFilename(filename) );
  693. std::string fullpath;
  694. for (const auto& searchIt : _searchPathArray)
  695. {
  696. for (const auto& resolutionIt : _searchResolutionsOrderArray)
  697. {
  698. fullpath = this->getPathForFilename(newFilename, resolutionIt, searchIt);
  699. if (!fullpath.empty())
  700. {
  701. // Using the filename passed in as key.
  702. _fullPathCache.emplace(filename, fullpath);
  703. return fullpath;
  704. }
  705. }
  706. }
  707. if(isPopupNotify()){
  708. CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.c_str());
  709. }
  710. // The file wasn't found, return empty string.
  711. return "";
  712. }
  713. std::string FileUtils::fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile)
  714. {
  715. return relativeFile.substr(0, relativeFile.rfind('/')+1) + getNewFilename(filename);
  716. }
  717. void FileUtils::setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder)
  718. {
  719. if (_searchResolutionsOrderArray == searchResolutionsOrder)
  720. {
  721. return;
  722. }
  723. bool existDefault = false;
  724. _fullPathCache.clear();
  725. _searchResolutionsOrderArray.clear();
  726. for(const auto& iter : searchResolutionsOrder)
  727. {
  728. std::string resolutionDirectory = iter;
  729. if (!existDefault && resolutionDirectory == "")
  730. {
  731. existDefault = true;
  732. }
  733. if (resolutionDirectory.length() > 0 && resolutionDirectory[resolutionDirectory.length()-1] != '/')
  734. {
  735. resolutionDirectory += "/";
  736. }
  737. _searchResolutionsOrderArray.push_back(resolutionDirectory);
  738. }
  739. if (!existDefault)
  740. {
  741. _searchResolutionsOrderArray.push_back("");
  742. }
  743. }
  744. void FileUtils::addSearchResolutionsOrder(const std::string &order,const bool front)
  745. {
  746. std::string resOrder = order;
  747. if (!resOrder.empty() && resOrder[resOrder.length()-1] != '/')
  748. resOrder.append("/");
  749. if (front) {
  750. _searchResolutionsOrderArray.insert(_searchResolutionsOrderArray.begin(), resOrder);
  751. } else {
  752. _searchResolutionsOrderArray.push_back(resOrder);
  753. }
  754. }
  755. const std::vector<std::string>& FileUtils::getSearchResolutionsOrder() const
  756. {
  757. return _searchResolutionsOrderArray;
  758. }
  759. const std::vector<std::string>& FileUtils::getSearchPaths() const
  760. {
  761. return _searchPathArray;
  762. }
  763. const std::vector<std::string>& FileUtils::getOriginalSearchPaths() const
  764. {
  765. return _originalSearchPaths;
  766. }
  767. void FileUtils::setWritablePath(const std::string& writablePath)
  768. {
  769. _writablePath = writablePath;
  770. }
  771. const std::string& FileUtils::getDefaultResourceRootPath() const
  772. {
  773. return _defaultResRootPath;
  774. }
  775. void FileUtils::setDefaultResourceRootPath(const std::string& path)
  776. {
  777. if (_defaultResRootPath != path)
  778. {
  779. _fullPathCache.clear();
  780. _defaultResRootPath = path;
  781. if (!_defaultResRootPath.empty() && _defaultResRootPath[_defaultResRootPath.length()-1] != '/')
  782. {
  783. _defaultResRootPath += '/';
  784. }
  785. // Updates search paths
  786. setSearchPaths(_originalSearchPaths);
  787. }
  788. }
  789. void FileUtils::setSearchPaths(const std::vector<std::string>& searchPaths)
  790. {
  791. bool existDefaultRootPath = false;
  792. _originalSearchPaths = searchPaths;
  793. _fullPathCache.clear();
  794. _searchPathArray.clear();
  795. for (const auto& path : _originalSearchPaths)
  796. {
  797. std::string prefix;
  798. std::string fullPath;
  799. if (!isAbsolutePath(path))
  800. { // Not an absolute path
  801. prefix = _defaultResRootPath;
  802. }
  803. fullPath = prefix + path;
  804. if (!path.empty() && path[path.length()-1] != '/')
  805. {
  806. fullPath += "/";
  807. }
  808. if (!existDefaultRootPath && path == _defaultResRootPath)
  809. {
  810. existDefaultRootPath = true;
  811. }
  812. _searchPathArray.push_back(fullPath);
  813. }
  814. if (!existDefaultRootPath)
  815. {
  816. //CCLOG("Default root path doesn't exist, adding it.");
  817. _searchPathArray.push_back(_defaultResRootPath);
  818. }
  819. }
  820. void FileUtils::addSearchPath(const std::string &searchpath,const bool front)
  821. {
  822. std::string prefix;
  823. if (!isAbsolutePath(searchpath))
  824. prefix = _defaultResRootPath;
  825. std::string path = prefix + searchpath;
  826. if (!path.empty() && path[path.length()-1] != '/')
  827. {
  828. path += "/";
  829. }
  830. if (front) {
  831. _originalSearchPaths.insert(_originalSearchPaths.begin(), searchpath);
  832. _searchPathArray.insert(_searchPathArray.begin(), path);
  833. } else {
  834. _originalSearchPaths.push_back(searchpath);
  835. if (!_searchPathArray.empty() && _searchPathArray[_searchPathArray.size()-1] == _defaultResRootPath)
  836. {
  837. _searchPathArray.insert(_searchPathArray.begin() + _searchPathArray.size() -1, path);
  838. }
  839. else
  840. {
  841. _searchPathArray.push_back(path);
  842. }
  843. }
  844. }
  845. void FileUtils::setFilenameLookupDictionary(const ValueMap& filenameLookupDict)
  846. {
  847. _fullPathCache.clear();
  848. _filenameLookupDict = filenameLookupDict;
  849. }
  850. void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename)
  851. {
  852. const std::string fullPath = fullPathForFilename(filename);
  853. if (!fullPath.empty())
  854. {
  855. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  856. if (!dict.empty())
  857. {
  858. ValueMap& metadata = dict["metadata"].asValueMap();
  859. int version = metadata["version"].asInt();
  860. if (version != 1)
  861. {
  862. CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %d. Filename: %s", version, filename.c_str());
  863. return;
  864. }
  865. setFilenameLookupDictionary( dict["filenames"].asValueMap());
  866. }
  867. }
  868. }
  869. std::string FileUtils::getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const
  870. {
  871. // get directory+filename, safely adding '/' as necessary
  872. std::string ret = directory;
  873. if (directory.size() && directory[directory.size()-1] != '/'){
  874. ret += '/';
  875. }
  876. ret += filename;
  877. // if the file doesn't exist, return an empty string
  878. if (!isFileExistInternal(ret)) {
  879. ret = "";
  880. }
  881. return ret;
  882. }
  883. bool FileUtils::isFileExist(const std::string& filename) const
  884. {
  885. if (isAbsolutePath(filename))
  886. {
  887. return isFileExistInternal(filename);
  888. }
  889. else
  890. {
  891. std::string fullpath = fullPathForFilename(filename);
  892. if (fullpath.empty())
  893. return false;
  894. else
  895. return true;
  896. }
  897. }
  898. void FileUtils::isFileExist(const std::string& filename, std::function<void(bool)> callback)
  899. {
  900. auto fullPath = fullPathForFilename(filename);
  901. performOperationOffthread([fullPath]() -> bool {
  902. return FileUtils::getInstance()->isFileExist(fullPath);
  903. }, std::move(callback));
  904. }
  905. bool FileUtils::isAbsolutePath(const std::string& path) const
  906. {
  907. return (path[0] == '/');
  908. }
  909. bool FileUtils::isDirectoryExist(const std::string& dirPath) const
  910. {
  911. CCASSERT(!dirPath.empty(), "Invalid path");
  912. if (isAbsolutePath(dirPath))
  913. {
  914. return isDirectoryExistInternal(dirPath);
  915. }
  916. // Already Cached ?
  917. auto cacheIter = _fullPathCache.find(dirPath);
  918. if( cacheIter != _fullPathCache.end() )
  919. {
  920. return isDirectoryExistInternal(cacheIter->second);
  921. }
  922. std::string fullpath;
  923. for (const auto& searchIt : _searchPathArray)
  924. {
  925. for (const auto& resolutionIt : _searchResolutionsOrderArray)
  926. {
  927. // searchPath + file_path + resourceDirectory
  928. fullpath = fullPathForFilename(searchIt + dirPath + resolutionIt);
  929. if (isDirectoryExistInternal(fullpath))
  930. {
  931. _fullPathCache.emplace(dirPath, fullpath);
  932. return true;
  933. }
  934. }
  935. }
  936. return false;
  937. }
  938. void FileUtils::isDirectoryExist(const std::string& fullPath, std::function<void(bool)> callback)
  939. {
  940. CCASSERT(isAbsolutePath(fullPath), "Async isDirectoryExist only accepts absolute file paths");
  941. performOperationOffthread([fullPath]() -> bool {
  942. return FileUtils::getInstance()->isDirectoryExist(fullPath);
  943. }, std::move(callback));
  944. }
  945. void FileUtils::createDirectory(const std::string& dirPath, std::function<void(bool)> callback)
  946. {
  947. performOperationOffthread([dirPath]() -> bool {
  948. return FileUtils::getInstance()->createDirectory(dirPath);
  949. }, std::move(callback));
  950. }
  951. void FileUtils::removeDirectory(const std::string& dirPath, std::function<void(bool)> callback)
  952. {
  953. performOperationOffthread([dirPath]() -> bool {
  954. return FileUtils::getInstance()->removeDirectory(dirPath);
  955. }, std::move(callback));
  956. }
  957. void FileUtils::removeFile(const std::string &filepath, std::function<void (bool)> callback)
  958. {
  959. auto fullPath = fullPathForFilename(filepath);
  960. performOperationOffthread([fullPath]() -> bool {
  961. return FileUtils::getInstance()->removeFile(fullPath);
  962. }, std::move(callback));
  963. }
  964. void FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name, std::function<void(bool)> callback)
  965. {
  966. performOperationOffthread([path, oldname, name]() -> bool {
  967. return FileUtils::getInstance()->renameFile(path, oldname, name);
  968. }, std::move(callback));
  969. }
  970. void FileUtils::renameFile(const std::string &oldfullpath, const std::string &newfullpath, std::function<void(bool)> callback)
  971. {
  972. performOperationOffthread([oldfullpath, newfullpath]() {
  973. return FileUtils::getInstance()->renameFile(oldfullpath, newfullpath);
  974. }, std::move(callback));
  975. }
  976. void FileUtils::getFileSize(const std::string &filepath, std::function<void(long)> callback)
  977. {
  978. auto fullPath = fullPathForFilename(filepath);
  979. performOperationOffthread([fullPath]() {
  980. return FileUtils::getInstance()->getFileSize(fullPath);
  981. }, std::move(callback));
  982. }
  983. std::vector<std::string> FileUtils::listFiles(const std::string& dirPath) const
  984. {
  985. std::string fullpath = fullPathForFilename(dirPath);
  986. std::vector<std::string> files;
  987. if (isDirectoryExist(fullpath))
  988. {
  989. tinydir_dir dir;
  990. #ifdef UNICODE
  991. unsigned int length = MultiByteToWideChar(CP_UTF8, 0, &fullpath[0], (int)fullpath.size(), NULL, 0);
  992. if (length != fullpath.size())
  993. {
  994. return files;
  995. }
  996. std::wstring fullpathstr(length, 0);
  997. MultiByteToWideChar(CP_UTF8, 0, &fullpath[0], (int)fullpath.size(), &fullpathstr[0], length);
  998. #else
  999. std::string fullpathstr = fullpath;
  1000. #endif
  1001. if (tinydir_open(&dir, &fullpathstr[0]) != -1)
  1002. {
  1003. while (dir.has_next)
  1004. {
  1005. tinydir_file file;
  1006. if (tinydir_readfile(&dir, &file) == -1)
  1007. {
  1008. // Error getting file
  1009. break;
  1010. }
  1011. #ifdef UNICODE
  1012. std::wstring path = file.path;
  1013. length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL);
  1014. std::string filepath;
  1015. if (length > 0)
  1016. {
  1017. filepath.resize(length);
  1018. WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), &filepath[0], length, NULL, NULL);
  1019. }
  1020. #else
  1021. std::string filepath = file.path;
  1022. #endif
  1023. if (file.is_dir)
  1024. {
  1025. filepath.append("/");
  1026. }
  1027. files.push_back(filepath);
  1028. if (tinydir_next(&dir) == -1)
  1029. {
  1030. // Error getting next file
  1031. break;
  1032. }
  1033. }
  1034. }
  1035. tinydir_close(&dir);
  1036. }
  1037. return files;
  1038. }
  1039. void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const
  1040. {
  1041. std::string fullpath = fullPathForFilename(dirPath);
  1042. if (isDirectoryExist(fullpath))
  1043. {
  1044. tinydir_dir dir;
  1045. #ifdef UNICODE
  1046. unsigned int length = MultiByteToWideChar(CP_UTF8, 0, &fullpath[0], (int)fullpath.size(), NULL, 0);
  1047. if (length != fullpath.size())
  1048. {
  1049. return;
  1050. }
  1051. std::wstring fullpathstr(length, 0);
  1052. MultiByteToWideChar(CP_UTF8, 0, &fullpath[0], (int)fullpath.size(), &fullpathstr[0], length);
  1053. #else
  1054. std::string fullpathstr = fullpath;
  1055. #endif
  1056. if (tinydir_open(&dir, &fullpathstr[0]) != -1)
  1057. {
  1058. while (dir.has_next)
  1059. {
  1060. tinydir_file file;
  1061. if (tinydir_readfile(&dir, &file) == -1)
  1062. {
  1063. // Error getting file
  1064. break;
  1065. }
  1066. #ifdef UNICODE
  1067. std::wstring path = file.path;
  1068. length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL);
  1069. std::string filepath;
  1070. if (length > 0)
  1071. {
  1072. filepath.resize(length);
  1073. WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), &filepath[0], length, NULL, NULL);
  1074. }
  1075. #else
  1076. std::string filepath = file.path;
  1077. #endif
  1078. if (file.name[0] != '.')
  1079. {
  1080. if (file.is_dir)
  1081. {
  1082. filepath.append("/");
  1083. files->push_back(filepath);
  1084. listFilesRecursively(filepath, files);
  1085. }
  1086. else
  1087. {
  1088. files->push_back(filepath);
  1089. }
  1090. }
  1091. if (tinydir_next(&dir) == -1)
  1092. {
  1093. // Error getting next file
  1094. break;
  1095. }
  1096. }
  1097. }
  1098. tinydir_close(&dir);
  1099. }
  1100. }
  1101. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  1102. // windows os implement should override in platform specific FileUtiles class
  1103. bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
  1104. {
  1105. CCASSERT(false, "FileUtils not support isDirectoryExistInternal");
  1106. return false;
  1107. }
  1108. bool FileUtils::createDirectory(const std::string& path)
  1109. {
  1110. CCASSERT(false, "FileUtils not support createDirectory");
  1111. return false;
  1112. }
  1113. bool FileUtils::removeDirectory(const std::string& path)
  1114. {
  1115. CCASSERT(false, "FileUtils not support removeDirectory");
  1116. return false;
  1117. }
  1118. bool FileUtils::removeFile(const std::string &path)
  1119. {
  1120. CCASSERT(false, "FileUtils not support removeFile");
  1121. return false;
  1122. }
  1123. bool FileUtils::renameFile(const std::string &oldfullpath, const std::string& newfullpath)
  1124. {
  1125. CCASSERT(false, "FileUtils not support renameFile");
  1126. return false;
  1127. }
  1128. bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
  1129. {
  1130. CCASSERT(false, "FileUtils not support renameFile");
  1131. return false;
  1132. }
  1133. std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
  1134. {
  1135. CCASSERT(false, "getSuitableFOpen should be override by platform FileUtils");
  1136. return filenameUtf8;
  1137. }
  1138. long FileUtils::getFileSize(const std::string &filepath)
  1139. {
  1140. CCASSERT(false, "getFileSize should be override by platform FileUtils");
  1141. return 0;
  1142. }
  1143. #else
  1144. // default implements for unix like os
  1145. #include <sys/types.h>
  1146. #include <errno.h>
  1147. #include <dirent.h>
  1148. bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
  1149. {
  1150. struct stat st;
  1151. if (stat(dirPath.c_str(), &st) == 0)
  1152. {
  1153. return S_ISDIR(st.st_mode);
  1154. }
  1155. return false;
  1156. }
  1157. bool FileUtils::createDirectory(const std::string& path)
  1158. {
  1159. CCASSERT(!path.empty(), "Invalid path");
  1160. if (isDirectoryExist(path))
  1161. return true;
  1162. // Split the path
  1163. size_t start = 0;
  1164. size_t found = path.find_first_of("/\\", start);
  1165. std::string subpath;
  1166. std::vector<std::string> dirs;
  1167. if (found != std::string::npos)
  1168. {
  1169. while (true)
  1170. {
  1171. subpath = path.substr(start, found - start + 1);
  1172. if (!subpath.empty())
  1173. dirs.push_back(subpath);
  1174. start = found+1;
  1175. found = path.find_first_of("/\\", start);
  1176. if (found == std::string::npos)
  1177. {
  1178. if (start < path.length())
  1179. {
  1180. dirs.push_back(path.substr(start));
  1181. }
  1182. break;
  1183. }
  1184. }
  1185. }
  1186. DIR *dir = NULL;
  1187. // Create path recursively
  1188. subpath = "";
  1189. for (const auto& iter : dirs)
  1190. {
  1191. subpath += iter;
  1192. dir = opendir(subpath.c_str());
  1193. if (!dir)
  1194. {
  1195. // directory doesn't exist, should create a new one
  1196. int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
  1197. if (ret != 0 && (errno != EEXIST))
  1198. {
  1199. // current directory can not be created, sub directories can not be created too
  1200. // should return
  1201. return false;
  1202. }
  1203. }
  1204. else
  1205. {
  1206. // directory exists, should close opened dir
  1207. closedir(dir);
  1208. }
  1209. }
  1210. return true;
  1211. }
  1212. bool FileUtils::removeDirectory(const std::string& path)
  1213. {
  1214. #if !defined(CC_TARGET_OS_TVOS)
  1215. std::string command = "rm -r ";
  1216. // Path may include space.
  1217. command += "\"" + path + "\"";
  1218. if (system(command.c_str()) >= 0)
  1219. return true;
  1220. else
  1221. return false;
  1222. #else
  1223. return false;
  1224. #endif
  1225. }
  1226. bool FileUtils::removeFile(const std::string &path)
  1227. {
  1228. if (remove(path.c_str())) {
  1229. return false;
  1230. } else {
  1231. return true;
  1232. }
  1233. }
  1234. bool FileUtils::renameFile(const std::string &oldfullpath, const std::string &newfullpath)
  1235. {
  1236. CCASSERT(!oldfullpath.empty(), "Invalid path");
  1237. CCASSERT(!newfullpath.empty(), "Invalid path");
  1238. int errorCode = rename(oldfullpath.c_str(), newfullpath.c_str());
  1239. if (0 != errorCode)
  1240. {
  1241. CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldfullpath.c_str(), newfullpath.c_str(), errorCode);
  1242. return false;
  1243. }
  1244. return true;
  1245. }
  1246. bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
  1247. {
  1248. CCASSERT(!path.empty(), "Invalid path");
  1249. std::string oldPath = path + oldname;
  1250. std::string newPath = path + name;
  1251. return this->renameFile(oldPath, newPath);
  1252. }
  1253. std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
  1254. {
  1255. return filenameUtf8;
  1256. }
  1257. long FileUtils::getFileSize(const std::string &filepath)
  1258. {
  1259. CCASSERT(!filepath.empty(), "Invalid path");
  1260. std::string fullpath = filepath;
  1261. if (!isAbsolutePath(filepath))
  1262. {
  1263. fullpath = fullPathForFilename(filepath);
  1264. if (fullpath.empty())
  1265. return 0;
  1266. }
  1267. struct stat info;
  1268. // Get data associated with "crt_stat.c":
  1269. int result = stat(fullpath.c_str(), &info);
  1270. // Check if statistics are valid:
  1271. if (result != 0)
  1272. {
  1273. // Failed
  1274. return -1;
  1275. }
  1276. else
  1277. {
  1278. return (long)(info.st_size);
  1279. }
  1280. }
  1281. #endif
  1282. //////////////////////////////////////////////////////////////////////////
  1283. // Notification support when getFileData from invalid file path.
  1284. //////////////////////////////////////////////////////////////////////////
  1285. static bool s_popupNotify = true;
  1286. void FileUtils::setPopupNotify(bool notify)
  1287. {
  1288. s_popupNotify = notify;
  1289. }
  1290. bool FileUtils::isPopupNotify() const
  1291. {
  1292. return s_popupNotify;
  1293. }
  1294. std::string FileUtils::getFileExtension(const std::string& filePath) const
  1295. {
  1296. std::string fileExtension;
  1297. size_t pos = filePath.find_last_of('.');
  1298. if (pos != std::string::npos)
  1299. {
  1300. fileExtension = filePath.substr(pos, filePath.length());
  1301. std::transform(fileExtension.begin(), fileExtension.end(), fileExtension.begin(), ::tolower);
  1302. }
  1303. return fileExtension;
  1304. }
  1305. void FileUtils::valueMapCompact(ValueMap& /*valueMap*/)
  1306. {
  1307. }
  1308. void FileUtils::valueVectorCompact(ValueVector& /*valueVector*/)
  1309. {
  1310. }
  1311. NS_CC_END