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

44 篇文章 0 订阅
44 篇文章 0 订阅

第一:读取沙盒下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);



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值