Read and Write of cocos2d-x Binary Files

Read and Write of cocos2d-x Binary Files

Welcome to upload, address of this post:

There are some ways to read binaries in cocos2d-x. The author encapsulates the method and sets the path to the writablePath path, which makes it easy to read the binaries he stores.The author did not find a way to output binary files in cocos2d-x, so he wrote his own.Here are the source implementations of the two methods:

Binary file reading:

  1. unsigned char* wkFileUtils::getFileByName(string pFileName){    
  2.     //Record CCFileUtils in cocos2d-x, setting whether pop-up prompt box is not found  
  3.     bool isNeedModifyPopupSetting  = CCFileUtils::sharedFileUtils()->isPopupNotify();  
  4.     //Close temporarily if prompted, as the read here may not find the file because it may not have been created  
  5.     if(isNeedModifyPopupSetting)  
  6.     {  
  7.         CCFileUtils::sharedFileUtils()->setPopupNotify(false);  
  8.     }   
  9.     //Get the path to the file and use getWritablePath because this is the file we need to store  
  10.     string path = CCFileUtils::sharedFileUtils()->getWritablePath() + pFileName;   
  11.     CCLog("path = %s",path.c_str());  
  12.     unsigned long len = 0;  
  13.     //Read the file, note the use of the parameter "r b", r for read, B for binary binary  
  14.     unsigned char* data = CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "rb", &len);  
  15.     CCLog("read data length = %d", len);  
  16.     //If the previous settings do not find the file prompted, change back to the original settings  
  17.     if(isNeedModifyPopupSetting)  
  18.     {  
  19.         CCFileUtils::sharedFileUtils()->setPopupNotify(true);  
  20.     }  
  21.     return data;    
  22. }  

Writing binaries:

  1. bool wkFileUtils::saveFile(unsigned char *pContent, string pFileName, int length){    
  2.     //Get Stored File Path  
  3.     string path = CCFileUtils::sharedFileUtils()->getWritablePath() + pFileName;    
  4.     CCLog("save file path = %s",path.c_str());    
  6.     //Create a file pointer, note to use the parameter "w b", w for write, B for binary binary, I used "w" before, IOS found no problems at that time, but there will be bug s on win32, change to "w b" is no problem  
  7.     FILE* file = fopen(path.c_str(), "wb");   
  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. }  

Tags: iOS

Posted on Sat, 21 Mar 2020 10:25:59 -0700 by phillips321