cocos2d-x 二进制文件的读写

欢迎转载,本帖地址:http://blog.csdn.net/wolfking_2009/article/details/10616069

cocos2d-x里面的二进制文件读取的方法是有的,作者对方法封装了下,将读取的路径设置到了writablePath路径上,这样方便读取自己存储的二进制文件。作者在cocos2d-x中没有找到二进制文件输出的方法,于是自己写了一个。下面就是两个方法的源码实现:

二进制文件的读取:

  1. unsigned char* wkFileUtils::getFileByName(string pFileName){    
  2.     //记录cocos2d-x中CCFileUtils,对于没有找到文件是否弹出提示框的设置  
  3.     bool isNeedModifyPopupSetting  = CCFileUtils::sharedFileUtils()->isPopupNotify();  
  4.     //如果有提示,就暂时关闭,因为这里的读取可能找不到该文件,因为该文件有可能还没有创建  
  5.     if(isNeedModifyPopupSetting)  
  6.     {  
  7.         CCFileUtils::sharedFileUtils()->setPopupNotify(false);  
  8.     }   
  9.     //获取文件的路径,使用getWritablePath是因为这个文件是我们需要存储的文件  
  10.     string path = CCFileUtils::sharedFileUtils()->getWritablePath() + pFileName;   
  11.     CCLog("path = %s",path.c_str());  
  12.     unsigned long len = 0;  
  13.     //读取文件,注意使用参数"rb",r表示read,b表示二进制binary  
  14.     unsigned char* data = CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "rb", &len);  
  15.     CCLog("read data length = %d", len);  
  16.     //如果以前设置找不到文件有提示,则改回原来的设置  
  17.     if(isNeedModifyPopupSetting)  
  18.     {  
  19.         CCFileUtils::sharedFileUtils()->setPopupNotify(true);  
  20.     }  
  21.     return data;    
  22. }  


二进制文件的写入:

  1. bool wkFileUtils::saveFile(unsigned char *pContent, string pFileName, int length){    
  2.     //获取储存的文件路径   
  3.     string path = CCFileUtils::sharedFileUtils()->getWritablePath() + pFileName;    
  4.     CCLog("save file path = %s",path.c_str());    
  5.   
  6.     //创建一个文件指针,注意要使用参数"wb",w表示write,b表示二进制binary,之前我使用的是"w",ios上当时没有发现问题,但是win32上会有bug,改成"wb"就没有问题了  
  7.     FILE* file = fopen(path.c_str(), "wb");   
  8.   
  9.     if (file) {   
  10.         fwrite(pContent, sizeof(unsigned char), length, file);  
  11.         fclose(file);    
  12.     }    
  13.     else  
  14.     {  
  15.         CCLog("save file error.");    
  16.     }    
  17.     return false;    
  18. }  
原文地址:https://www.cnblogs.com/shiweihappy/p/4246451.html