CCFileUtils.cpp 43 KB

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