CCFileUtils.cpp 42 KB

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