现在的位置: 首页 > 综合 > 正文

cocos2d-x 读写xml文件,沙盒路径下超详细攻略(object向c++转型系列教程5)

2013年12月08日 ⁄ 综合 ⁄ 共 1189字 ⁄ 字号 评论关闭

第一:读取沙盒下xml文件

1,先取得访问路劲:

std::string
documentPath =
CCFileUtils::getWriteablePath();

string fileName = "fileName.xml";

string filePath = documentPath
+ fileName;

2,读取xml文件为string  

           string path = filePath;

           FILE *fp =fopen(path.c_str(),"r");//根据路径打开文件

            

    char *pchBuf = NULL;//将要取得的字符串

            int  nLen = 0;//要取得的字符串长度

           fseek(fp,0,SEEK_END);//文件指针移到文件尾

            nLen =ftell(fp); //得到当前指针位置,即是文件的长度

           rewind(fp);   //文件指针恢复到文件头位置

            

            //动态申请空间,为保存字符串结尾标志\0,多申请一个字符的空间

            pchBuf = (char*)malloc(sizeof(char)*nLen+1);

           if(!pchBuf)

            {

               perror("内存不够!\n");

               exit(0);

            }

            

            //读取文件内容//读取的长度和源文件长度有可能有出入,这里自动调整 nLen

            nLen =fread(pchBuf,sizeof(char), nLen, fp);

            

            pchBuf[nLen] ='\0';//添加字符串结尾标志

            

           printf("%s\n", pchBuf);//把读取的内容输出到屏幕看看

           string detailStr = pchBuf;

           fclose(fp); //关闭文件

           free(pchBuf);//释放空间

            

第二:写入xml文件到沙盒下

//要保存的xml

    string xmlStr = "<xml>MyXml<xml>";

   constchar * aChar = xmlStr.c_str();

//取得文件储存的位置

std::string documentPath
CCFileUtils::getWriteablePath();

string fileName = "fileName.xml";

string filePath = documentPath + fileName;

//保存字符串为xml文件

string path = filePath;

FILE *fp =fopen(path.c_str(),"w");

    

    

fputs(aChar, fp);

fclose(fp);

【上篇】
【下篇】

抱歉!评论已关闭.