转载请注明:http://blog.csdn.net/einsteinlike/article/details/41543237
在ios_mac中 读取xml时会这么写:
tinyxml2::XMLDocument configXML;std::string path = FileUtils::getInstance()->fullPathForFilename("maps/maps.xml"); CCLog("liujianlog : %s " ,path.c_str());configXML.LoadFile(path.c_str());
但是移植到android后这部分就会出现闪退,通过log看出是loadFile内部异常:
XMLError XMLDocument::LoadFile( const char* filename )
{DeleteChildren();InitDocument();FILE* fp = 0;#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)errno_t err = fopen_s(&fp, filename, "rb" );if ( !fp || err) {
#elsefp = fopen( filename, "rb" );//返回了NULLif ( !fp) {
#endifSetError( XML_ERROR_FILE_NOT_FOUND, filename, 0 );//就是这里return _errorID;}LoadFile( fp );fclose( fp );return _errorID;
}
这里就要说一下fopen的用法了,android下是支持标准库中的fopen的,但是,fopen必须是一个暴露出来的文件,而cocos将资源文件都打包在了apk中!所以fopen读取不到了就。
解决方法是使用 getFileDataFromZip ;cocos的fileutils_android中的getFileData内部就是使用的这个方法,所以可以这样写:
long size;char *pFileContent = (char*)FileUtils::getInstance()->getFileData( "maps/maps.xml" , "r", &size);tinyxml2::XMLDocument configXML;configXML.Parse(pFileContent, size);
参考:
http://codingnow.cn/cocos2d-x/939.html