CCFileUtils.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  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. #ifdef MINIZIP_FROM_SYSTEM
  30. #include <minizip/unzip.h>
  31. #else // from our embedded sources
  32. #include "unzip.h"
  33. #endif
  34. #include <sys/stat.h>
  35. #include "../common/BigFile.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) override
  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) override
  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. //add by yuntao
  563. bool needDec = false;
  564. if(BigFile::inited){
  565. ssize_t size;
  566. const unsigned char *dbuffer = BigFile::getInstance()->getDataFromCache(fullPath, &size);
  567. if (dbuffer) {
  568. buffer->resize(size);
  569. memcpy(buffer->buffer(), dbuffer, size);
  570. return Status::OK;
  571. }
  572. needDec = BigFile::getInstance()->needDecode(fullPath);
  573. }
  574. FILE *fp = fopen(fs->getSuitableFOpen(fullPath).c_str(), "rb");
  575. if (!fp)
  576. return Status::OpenFailed;
  577. #if defined(_MSC_VER)
  578. auto descriptor = _fileno(fp);
  579. #else
  580. auto descriptor = fileno(fp);
  581. #endif
  582. struct stat statBuf;
  583. if (fstat(descriptor, &statBuf) == -1) {
  584. fclose(fp);
  585. return Status::ReadFailed;
  586. }
  587. size_t size = statBuf.st_size;
  588. buffer->resize(size);
  589. size_t readsize = fread(buffer->buffer(), 1, size, fp);
  590. fclose(fp);
  591. if (readsize < size) {
  592. buffer->resize(readsize);
  593. return Status::ReadFailed;
  594. }
  595. //add by yuntao
  596. if(needDec){
  597. BigFile::getInstance()->rc4_crypt((unsigned char *)buffer->buffer(), size);
  598. BigFile::getInstance()->saveDataToCache(fullPath, (unsigned char *)buffer->buffer(), size);
  599. }
  600. return Status::OK;
  601. }
  602. unsigned char* FileUtils::getFileData(const std::string& filename, const char* mode, ssize_t *size)
  603. {
  604. CCASSERT(!filename.empty() && size != nullptr && mode != nullptr, "Invalid parameters.");
  605. (void)(mode); // mode is unused, as we do not support text mode any more...
  606. Data d;
  607. if (getContents(filename, &d) != Status::OK) {
  608. *size = 0;
  609. return nullptr;
  610. }
  611. return d.takeBuffer(size);
  612. }
  613. unsigned char* FileUtils::getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size)
  614. {
  615. unsigned char * buffer = nullptr;
  616. unzFile file = nullptr;
  617. *size = 0;
  618. do
  619. {
  620. CC_BREAK_IF(zipFilePath.empty());
  621. file = unzOpen(FileUtils::getInstance()->getSuitableFOpen(zipFilePath).c_str());
  622. CC_BREAK_IF(!file);
  623. // FIXME: Other platforms should use upstream minizip like mingw-w64
  624. // minizip 1.2.0 is same with other platforms
  625. int ret = unzLocateFile(file, filename.c_str(), nullptr);
  626. CC_BREAK_IF(UNZ_OK != ret);
  627. char filePathA[260];
  628. unz_file_info fileInfo;
  629. ret = unzGetCurrentFileInfo(file, &fileInfo, filePathA, sizeof(filePathA), nullptr, 0, nullptr, 0);
  630. CC_BREAK_IF(UNZ_OK != ret);
  631. ret = unzOpenCurrentFile(file);
  632. CC_BREAK_IF(UNZ_OK != ret);
  633. buffer = (unsigned char*)malloc(fileInfo.uncompressed_size);
  634. int CC_UNUSED readedSize = unzReadCurrentFile(file, buffer, static_cast<unsigned>(fileInfo.uncompressed_size));
  635. CCASSERT(readedSize == 0 || readedSize == (int)fileInfo.uncompressed_size, "the file size is wrong");
  636. *size = fileInfo.uncompressed_size;
  637. unzCloseCurrentFile(file);
  638. } while (0);
  639. if (file)
  640. {
  641. unzClose(file);
  642. }
  643. return buffer;
  644. }
  645. void FileUtils::writeValueMapToFile(ValueMap dict, const std::string& fullPath, std::function<void(bool)> callback)
  646. {
  647. performOperationOffthread([fullPath](const ValueMap& dictIn) -> bool {
  648. return FileUtils::getInstance()->writeValueMapToFile(dictIn, fullPath);
  649. }, std::move(callback), std::move(dict));
  650. }
  651. void FileUtils::writeValueVectorToFile(ValueVector vecData, const std::string& fullPath, std::function<void(bool)> callback)
  652. {
  653. performOperationOffthread([fullPath] (const ValueVector& vecDataIn) -> bool {
  654. return FileUtils::getInstance()->writeValueVectorToFile(vecDataIn, fullPath);
  655. }, std::move(callback), std::move(vecData));
  656. }
  657. std::string FileUtils::getNewFilename(const std::string &filename) const
  658. {
  659. std::string newFileName;
  660. // in Lookup Filename dictionary ?
  661. auto iter = _filenameLookupDict.find(filename);
  662. if (iter == _filenameLookupDict.end())
  663. {
  664. newFileName = filename;
  665. }
  666. else
  667. {
  668. newFileName = iter->second.asString();
  669. }
  670. return newFileName;
  671. }
  672. std::string FileUtils::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const
  673. {
  674. std::string file = filename;
  675. std::string file_path = "";
  676. size_t pos = filename.find_last_of("/");
  677. if (pos != std::string::npos)
  678. {
  679. file_path = filename.substr(0, pos+1);
  680. file = filename.substr(pos+1);
  681. }
  682. // searchPath + file_path + resourceDirectory
  683. std::string path = searchPath;
  684. path += file_path;
  685. path += resolutionDirectory;
  686. //add by yuntao
  687. // CCLOG("\n<><> %s | %s\n",path.c_str(),file.c_str());
  688. if(BigFile::inited){
  689. BigFile::getInstance()->targetFileNameFromDirAndFile(path,file);
  690. }
  691. path = getFullPathForDirectoryAndFilename(path, file);
  692. return path;
  693. }
  694. std::string FileUtils::fullPathForFilename(const std::string &filename) const
  695. {
  696. if (filename.empty())
  697. {
  698. return "";
  699. }
  700. if (isAbsolutePath(filename))
  701. {
  702. return filename;
  703. }
  704. // Already Cached ?
  705. auto cacheIter = _fullPathCache.find(filename);
  706. if(cacheIter != _fullPathCache.end())
  707. {
  708. return cacheIter->second;
  709. }
  710. // Get the new file name.
  711. const std::string newFilename( getNewFilename(filename) );
  712. std::string fullpath;
  713. for (const auto& searchIt : _searchPathArray)
  714. {
  715. for (const auto& resolutionIt : _searchResolutionsOrderArray)
  716. {
  717. fullpath = this->getPathForFilename(newFilename, resolutionIt, searchIt);
  718. if (!fullpath.empty())
  719. {
  720. // Using the filename passed in as key.
  721. _fullPathCache.emplace(filename, fullpath);
  722. return fullpath;
  723. }
  724. }
  725. }
  726. if(isPopupNotify()){
  727. CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.c_str());
  728. }
  729. // The file wasn't found, return empty string.
  730. return "";
  731. }
  732. std::string FileUtils::fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile)
  733. {
  734. return relativeFile.substr(0, relativeFile.rfind('/')+1) + getNewFilename(filename);
  735. }
  736. void FileUtils::setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder)
  737. {
  738. if (_searchResolutionsOrderArray == searchResolutionsOrder)
  739. {
  740. return;
  741. }
  742. bool existDefault = false;
  743. _fullPathCache.clear();
  744. _searchResolutionsOrderArray.clear();
  745. for(const auto& iter : searchResolutionsOrder)
  746. {
  747. std::string resolutionDirectory = iter;
  748. if (!existDefault && resolutionDirectory == "")
  749. {
  750. existDefault = true;
  751. }
  752. if (resolutionDirectory.length() > 0 && resolutionDirectory[resolutionDirectory.length()-1] != '/')
  753. {
  754. resolutionDirectory += "/";
  755. }
  756. _searchResolutionsOrderArray.push_back(resolutionDirectory);
  757. }
  758. if (!existDefault)
  759. {
  760. _searchResolutionsOrderArray.push_back("");
  761. }
  762. }
  763. void FileUtils::addSearchResolutionsOrder(const std::string &order,const bool front)
  764. {
  765. std::string resOrder = order;
  766. if (!resOrder.empty() && resOrder[resOrder.length()-1] != '/')
  767. resOrder.append("/");
  768. if (front) {
  769. _searchResolutionsOrderArray.insert(_searchResolutionsOrderArray.begin(), resOrder);
  770. } else {
  771. _searchResolutionsOrderArray.push_back(resOrder);
  772. }
  773. }
  774. const std::vector<std::string>& FileUtils::getSearchResolutionsOrder() const
  775. {
  776. return _searchResolutionsOrderArray;
  777. }
  778. const std::vector<std::string>& FileUtils::getSearchPaths() const
  779. {
  780. return _searchPathArray;
  781. }
  782. const std::vector<std::string>& FileUtils::getOriginalSearchPaths() const
  783. {
  784. return _originalSearchPaths;
  785. }
  786. void FileUtils::setWritablePath(const std::string& writablePath)
  787. {
  788. _writablePath = writablePath;
  789. }
  790. const std::string& FileUtils::getDefaultResourceRootPath() const
  791. {
  792. return _defaultResRootPath;
  793. }
  794. void FileUtils::setDefaultResourceRootPath(const std::string& path)
  795. {
  796. if (_defaultResRootPath != path)
  797. {
  798. _fullPathCache.clear();
  799. _defaultResRootPath = path;
  800. if (!_defaultResRootPath.empty() && _defaultResRootPath[_defaultResRootPath.length()-1] != '/')
  801. {
  802. _defaultResRootPath += '/';
  803. }
  804. // Updates search paths
  805. setSearchPaths(_originalSearchPaths);
  806. }
  807. }
  808. void FileUtils::setSearchPaths(const std::vector<std::string>& searchPaths)
  809. {
  810. bool existDefaultRootPath = false;
  811. _originalSearchPaths = searchPaths;
  812. _fullPathCache.clear();
  813. _searchPathArray.clear();
  814. for (const auto& path : _originalSearchPaths)
  815. {
  816. std::string prefix;
  817. std::string fullPath;
  818. if (!isAbsolutePath(path))
  819. { // Not an absolute path
  820. prefix = _defaultResRootPath;
  821. }
  822. fullPath = prefix + path;
  823. if (!path.empty() && path[path.length()-1] != '/')
  824. {
  825. fullPath += "/";
  826. }
  827. if (!existDefaultRootPath && path == _defaultResRootPath)
  828. {
  829. existDefaultRootPath = true;
  830. }
  831. _searchPathArray.push_back(fullPath);
  832. }
  833. if (!existDefaultRootPath)
  834. {
  835. //CCLOG("Default root path doesn't exist, adding it.");
  836. _searchPathArray.push_back(_defaultResRootPath);
  837. }
  838. }
  839. void FileUtils::addSearchPath(const std::string &searchpath,const bool front)
  840. {
  841. std::string prefix;
  842. if (!isAbsolutePath(searchpath))
  843. prefix = _defaultResRootPath;
  844. std::string path = prefix + searchpath;
  845. if (!path.empty() && path[path.length()-1] != '/')
  846. {
  847. path += "/";
  848. }
  849. if (front) {
  850. _originalSearchPaths.insert(_originalSearchPaths.begin(), searchpath);
  851. _searchPathArray.insert(_searchPathArray.begin(), path);
  852. } else {
  853. _originalSearchPaths.push_back(searchpath);
  854. if (!_searchPathArray.empty() && _searchPathArray[_searchPathArray.size()-1] == _defaultResRootPath)
  855. {
  856. _searchPathArray.insert(_searchPathArray.begin() + _searchPathArray.size() -1, path);
  857. }
  858. else
  859. {
  860. _searchPathArray.push_back(path);
  861. }
  862. }
  863. }
  864. void FileUtils::setFilenameLookupDictionary(const ValueMap& filenameLookupDict)
  865. {
  866. _fullPathCache.clear();
  867. _filenameLookupDict = filenameLookupDict;
  868. }
  869. void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string &filename)
  870. {
  871. const std::string fullPath = fullPathForFilename(filename);
  872. if (!fullPath.empty())
  873. {
  874. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  875. if (!dict.empty())
  876. {
  877. ValueMap& metadata = dict["metadata"].asValueMap();
  878. int version = metadata["version"].asInt();
  879. if (version != 1)
  880. {
  881. CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %d. Filename: %s", version, filename.c_str());
  882. return;
  883. }
  884. setFilenameLookupDictionary( dict["filenames"].asValueMap());
  885. }
  886. }
  887. }
  888. std::string FileUtils::getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const
  889. {
  890. // get directory+filename, safely adding '/' as necessary
  891. std::string ret = directory;
  892. if (directory.size() && directory[directory.size()-1] != '/'){
  893. ret += '/';
  894. }
  895. ret += filename;
  896. // if the file doesn't exist, return an empty string
  897. if (!isFileExistInternal(ret)) {
  898. ret = "";
  899. }
  900. return ret;
  901. }
  902. bool FileUtils::isFileExist(const std::string& filename) const
  903. {
  904. if (isAbsolutePath(filename))
  905. {
  906. return isFileExistInternal(filename);
  907. }
  908. else
  909. {
  910. std::string fullpath = fullPathForFilename(filename);
  911. if (fullpath.empty())
  912. return false;
  913. else
  914. return true;
  915. }
  916. }
  917. void FileUtils::isFileExist(const std::string& filename, std::function<void(bool)> callback)
  918. {
  919. auto fullPath = fullPathForFilename(filename);
  920. performOperationOffthread([fullPath]() -> bool {
  921. return FileUtils::getInstance()->isFileExist(fullPath);
  922. }, std::move(callback));
  923. }
  924. bool FileUtils::isAbsolutePath(const std::string& path) const
  925. {
  926. return (path[0] == '/');
  927. }
  928. bool FileUtils::isDirectoryExist(const std::string& dirPath) const
  929. {
  930. CCASSERT(!dirPath.empty(), "Invalid path");
  931. if (isAbsolutePath(dirPath))
  932. {
  933. return isDirectoryExistInternal(dirPath);
  934. }
  935. // Already Cached ?
  936. auto cacheIter = _fullPathCache.find(dirPath);
  937. if( cacheIter != _fullPathCache.end() )
  938. {
  939. return isDirectoryExistInternal(cacheIter->second);
  940. }
  941. std::string fullpath;
  942. for (const auto& searchIt : _searchPathArray)
  943. {
  944. for (const auto& resolutionIt : _searchResolutionsOrderArray)
  945. {
  946. // searchPath + file_path + resourceDirectory
  947. fullpath = fullPathForFilename(searchIt + dirPath + resolutionIt);
  948. if (isDirectoryExistInternal(fullpath))
  949. {
  950. _fullPathCache.emplace(dirPath, fullpath);
  951. return true;
  952. }
  953. }
  954. }
  955. return false;
  956. }
  957. void FileUtils::isDirectoryExist(const std::string& fullPath, std::function<void(bool)> callback)
  958. {
  959. CCASSERT(isAbsolutePath(fullPath), "Async isDirectoryExist only accepts absolute file paths");
  960. performOperationOffthread([fullPath]() -> bool {
  961. return FileUtils::getInstance()->isDirectoryExist(fullPath);
  962. }, std::move(callback));
  963. }
  964. void FileUtils::createDirectory(const std::string& dirPath, std::function<void(bool)> callback)
  965. {
  966. performOperationOffthread([dirPath]() -> bool {
  967. return FileUtils::getInstance()->createDirectory(dirPath);
  968. }, std::move(callback));
  969. }
  970. void FileUtils::removeDirectory(const std::string& dirPath, std::function<void(bool)> callback)
  971. {
  972. performOperationOffthread([dirPath]() -> bool {
  973. return FileUtils::getInstance()->removeDirectory(dirPath);
  974. }, std::move(callback));
  975. }
  976. void FileUtils::removeFile(const std::string &filepath, std::function<void (bool)> callback)
  977. {
  978. auto fullPath = fullPathForFilename(filepath);
  979. performOperationOffthread([fullPath]() -> bool {
  980. return FileUtils::getInstance()->removeFile(fullPath);
  981. }, std::move(callback));
  982. }
  983. void FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name, std::function<void(bool)> callback)
  984. {
  985. performOperationOffthread([path, oldname, name]() -> bool {
  986. return FileUtils::getInstance()->renameFile(path, oldname, name);
  987. }, std::move(callback));
  988. }
  989. void FileUtils::renameFile(const std::string &oldfullpath, const std::string &newfullpath, std::function<void(bool)> callback)
  990. {
  991. performOperationOffthread([oldfullpath, newfullpath]() {
  992. return FileUtils::getInstance()->renameFile(oldfullpath, newfullpath);
  993. }, std::move(callback));
  994. }
  995. void FileUtils::getFileSize(const std::string &filepath, std::function<void(long)> callback)
  996. {
  997. auto fullPath = fullPathForFilename(filepath);
  998. performOperationOffthread([fullPath]() {
  999. return FileUtils::getInstance()->getFileSize(fullPath);
  1000. }, std::move(callback));
  1001. }
  1002. void FileUtils::listFilesAsync(const std::string& dirPath, std::function<void(std::vector<std::string>)> callback) const
  1003. {
  1004. auto fullPath = fullPathForFilename(dirPath);
  1005. performOperationOffthread([fullPath]() {
  1006. return FileUtils::getInstance()->listFiles(fullPath);
  1007. }, std::move(callback));
  1008. }
  1009. void FileUtils::listFilesRecursivelyAsync(const std::string& dirPath, std::function<void(std::vector<std::string>)> callback) const
  1010. {
  1011. auto fullPath = fullPathForFilename(dirPath);
  1012. performOperationOffthread([fullPath]() {
  1013. std::vector<std::string> retval;
  1014. FileUtils::getInstance()->listFilesRecursively(fullPath, &retval);
  1015. return retval;
  1016. }, std::move(callback));
  1017. }
  1018. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  1019. // windows os implement should override in platform specific FileUtiles class
  1020. bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
  1021. {
  1022. CCASSERT(false, "FileUtils not support isDirectoryExistInternal");
  1023. return false;
  1024. }
  1025. bool FileUtils::createDirectory(const std::string& path)
  1026. {
  1027. CCASSERT(false, "FileUtils not support createDirectory");
  1028. return false;
  1029. }
  1030. bool FileUtils::removeDirectory(const std::string& path)
  1031. {
  1032. CCASSERT(false, "FileUtils not support removeDirectory");
  1033. return false;
  1034. }
  1035. bool FileUtils::removeFile(const std::string &path)
  1036. {
  1037. CCASSERT(false, "FileUtils not support removeFile");
  1038. return false;
  1039. }
  1040. bool FileUtils::renameFile(const std::string &oldfullpath, const std::string& newfullpath)
  1041. {
  1042. CCASSERT(false, "FileUtils not support renameFile");
  1043. return false;
  1044. }
  1045. bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
  1046. {
  1047. CCASSERT(false, "FileUtils not support renameFile");
  1048. return false;
  1049. }
  1050. std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
  1051. {
  1052. CCASSERT(false, "getSuitableFOpen should be override by platform FileUtils");
  1053. return filenameUtf8;
  1054. }
  1055. long FileUtils::getFileSize(const std::string &filepath)
  1056. {
  1057. CCASSERT(false, "getFileSize should be override by platform FileUtils");
  1058. return 0;
  1059. }
  1060. std::vector<std::string> FileUtils::listFiles(const std::string& dirPath) const
  1061. {
  1062. CCASSERT(false, "FileUtils not support listFiles");
  1063. return std::vector<std::string>();
  1064. }
  1065. void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const
  1066. {
  1067. CCASSERT(false, "FileUtils not support listFilesRecursively");
  1068. return;
  1069. }
  1070. #else
  1071. #include "tinydir/tinydir.h"
  1072. // default implements for unix like os
  1073. #include <sys/types.h>
  1074. #include <errno.h>
  1075. #include <dirent.h>
  1076. // android doesn't have ftw.h
  1077. #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
  1078. #include <ftw.h>
  1079. #endif
  1080. bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
  1081. {
  1082. struct stat st;
  1083. if (stat(dirPath.c_str(), &st) == 0)
  1084. {
  1085. return S_ISDIR(st.st_mode);
  1086. }
  1087. return false;
  1088. }
  1089. bool FileUtils::createDirectory(const std::string& path)
  1090. {
  1091. CCASSERT(!path.empty(), "Invalid path");
  1092. if (isDirectoryExist(path))
  1093. return true;
  1094. // Split the path
  1095. size_t start = 0;
  1096. size_t found = path.find_first_of("/\\", start);
  1097. std::string subpath;
  1098. std::vector<std::string> dirs;
  1099. if (found != std::string::npos)
  1100. {
  1101. while (true)
  1102. {
  1103. subpath = path.substr(start, found - start + 1);
  1104. if (!subpath.empty())
  1105. dirs.push_back(subpath);
  1106. start = found+1;
  1107. found = path.find_first_of("/\\", start);
  1108. if (found == std::string::npos)
  1109. {
  1110. if (start < path.length())
  1111. {
  1112. dirs.push_back(path.substr(start));
  1113. }
  1114. break;
  1115. }
  1116. }
  1117. }
  1118. DIR *dir = NULL;
  1119. // Create path recursively
  1120. subpath = "";
  1121. for (const auto& iter : dirs)
  1122. {
  1123. subpath += iter;
  1124. dir = opendir(subpath.c_str());
  1125. if (!dir)
  1126. {
  1127. // directory doesn't exist, should create a new one
  1128. int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
  1129. if (ret != 0 && (errno != EEXIST))
  1130. {
  1131. // current directory can not be created, sub directories can not be created too
  1132. // should return
  1133. return false;
  1134. }
  1135. }
  1136. else
  1137. {
  1138. // directory exists, should close opened dir
  1139. closedir(dir);
  1140. }
  1141. }
  1142. return true;
  1143. }
  1144. namespace
  1145. {
  1146. #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
  1147. int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  1148. {
  1149. int rv = remove(fpath);
  1150. if (rv)
  1151. perror(fpath);
  1152. return rv;
  1153. }
  1154. #endif
  1155. }
  1156. bool FileUtils::removeDirectory(const std::string& path)
  1157. {
  1158. #if !defined(CC_TARGET_OS_TVOS)
  1159. #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
  1160. if (nftw(path.c_str(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS) == -1)
  1161. return false;
  1162. else
  1163. return true;
  1164. #else
  1165. std::string command = "rm -r ";
  1166. // Path may include space.
  1167. command += "\"" + path + "\"";
  1168. if (system(command.c_str()) >= 0)
  1169. return true;
  1170. else
  1171. return false;
  1172. #endif // (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
  1173. #else
  1174. return false;
  1175. #endif // !defined(CC_TARGET_OS_TVOS)
  1176. }
  1177. bool FileUtils::removeFile(const std::string &path)
  1178. {
  1179. if (remove(path.c_str())) {
  1180. return false;
  1181. } else {
  1182. return true;
  1183. }
  1184. }
  1185. bool FileUtils::renameFile(const std::string &oldfullpath, const std::string &newfullpath)
  1186. {
  1187. CCASSERT(!oldfullpath.empty(), "Invalid path");
  1188. CCASSERT(!newfullpath.empty(), "Invalid path");
  1189. int errorCode = rename(oldfullpath.c_str(), newfullpath.c_str());
  1190. if (0 != errorCode)
  1191. {
  1192. CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldfullpath.c_str(), newfullpath.c_str(), errorCode);
  1193. return false;
  1194. }
  1195. return true;
  1196. }
  1197. bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
  1198. {
  1199. CCASSERT(!path.empty(), "Invalid path");
  1200. std::string oldPath = path + oldname;
  1201. std::string newPath = path + name;
  1202. return this->renameFile(oldPath, newPath);
  1203. }
  1204. std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
  1205. {
  1206. return filenameUtf8;
  1207. }
  1208. long FileUtils::getFileSize(const std::string &filepath)
  1209. {
  1210. CCASSERT(!filepath.empty(), "Invalid path");
  1211. std::string fullpath = filepath;
  1212. if (!isAbsolutePath(filepath))
  1213. {
  1214. fullpath = fullPathForFilename(filepath);
  1215. if (fullpath.empty())
  1216. return 0;
  1217. }
  1218. struct stat info;
  1219. // Get data associated with "crt_stat.c":
  1220. int result = stat(fullpath.c_str(), &info);
  1221. // Check if statistics are valid:
  1222. if (result != 0)
  1223. {
  1224. // Failed
  1225. return -1;
  1226. }
  1227. else
  1228. {
  1229. return (long)(info.st_size);
  1230. }
  1231. }
  1232. std::vector<std::string> FileUtils::listFiles(const std::string& dirPath) const
  1233. {
  1234. std::vector<std::string> files;
  1235. std::string fullpath = fullPathForFilename(dirPath);
  1236. if (isDirectoryExist(fullpath))
  1237. {
  1238. tinydir_dir dir;
  1239. std::string fullpathstr = fullpath;
  1240. if (tinydir_open(&dir, &fullpathstr[0]) != -1)
  1241. {
  1242. while (dir.has_next)
  1243. {
  1244. tinydir_file file;
  1245. if (tinydir_readfile(&dir, &file) == -1)
  1246. {
  1247. // Error getting file
  1248. break;
  1249. }
  1250. std::string filepath = file.path;
  1251. if (file.is_dir)
  1252. {
  1253. filepath.append("/");
  1254. }
  1255. files.push_back(filepath);
  1256. if (tinydir_next(&dir) == -1)
  1257. {
  1258. // Error getting next file
  1259. break;
  1260. }
  1261. }
  1262. }
  1263. tinydir_close(&dir);
  1264. }
  1265. return files;
  1266. }
  1267. void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const
  1268. {
  1269. std::string fullpath = fullPathForFilename(dirPath);
  1270. if (isDirectoryExist(fullpath))
  1271. {
  1272. tinydir_dir dir;
  1273. std::string fullpathstr = fullpath;
  1274. if (tinydir_open(&dir, &fullpathstr[0]) != -1)
  1275. {
  1276. while (dir.has_next)
  1277. {
  1278. tinydir_file file;
  1279. if (tinydir_readfile(&dir, &file) == -1)
  1280. {
  1281. // Error getting file
  1282. break;
  1283. }
  1284. std::string fileName = file.name;
  1285. if (fileName != "." && fileName != "..")
  1286. {
  1287. std::string filepath = file.path;
  1288. if (file.is_dir)
  1289. {
  1290. filepath.append("/");
  1291. files->push_back(filepath);
  1292. listFilesRecursively(filepath, files);
  1293. }
  1294. else
  1295. {
  1296. files->push_back(filepath);
  1297. }
  1298. }
  1299. if (tinydir_next(&dir) == -1)
  1300. {
  1301. // Error getting next file
  1302. break;
  1303. }
  1304. }
  1305. }
  1306. tinydir_close(&dir);
  1307. }
  1308. }
  1309. #endif
  1310. //////////////////////////////////////////////////////////////////////////
  1311. // Notification support when getFileData from invalid file path.
  1312. //////////////////////////////////////////////////////////////////////////
  1313. static bool s_popupNotify = true;
  1314. void FileUtils::setPopupNotify(bool notify)
  1315. {
  1316. s_popupNotify = notify;
  1317. }
  1318. bool FileUtils::isPopupNotify() const
  1319. {
  1320. return s_popupNotify;
  1321. }
  1322. std::string FileUtils::getFileExtension(const std::string& filePath) const
  1323. {
  1324. std::string fileExtension;
  1325. size_t pos = filePath.find_last_of('.');
  1326. if (pos != std::string::npos)
  1327. {
  1328. fileExtension = filePath.substr(pos, filePath.length());
  1329. std::transform(fileExtension.begin(), fileExtension.end(), fileExtension.begin(), ::tolower);
  1330. }
  1331. return fileExtension;
  1332. }
  1333. void FileUtils::valueMapCompact(ValueMap& /*valueMap*/)
  1334. {
  1335. }
  1336. void FileUtils::valueVectorCompact(ValueVector& /*valueVector*/)
  1337. {
  1338. }
  1339. NS_CC_END