轉自:http://blog.csdn.net/wolfking_2009/article/details/10616069
cocos2d-x里面的二進制文件讀取的方法是有的,作者對方法封裝了下,將讀取的路徑設置到了writablePath路徑上,這樣方便讀取自己存儲的二進制文件。作者在cocos2d-x中沒有找到二進制文件輸出的方法,於是自己寫了一個。下面就是兩個方法的源碼實現:
二進制文件的讀取:
unsigned char* wkFileUtils::getFileByName(string pFileName){ //記錄cocos2d-x中CCFileUtils,對於沒有找到文件是否彈出提示框的設置 bool isNeedModifyPopupSetting = CCFileUtils::sharedFileUtils()->isPopupNotify(); //如果有提示,就暫時關閉,因為這里的讀取可能找不到該文件,因為該文件有可能還沒有創建 if(isNeedModifyPopupSetting) { CCFileUtils::sharedFileUtils()->setPopupNotify(false); } //獲取文件的路徑,使用getWritablePath是因為這個文件是我們需要存儲的文件 string path = CCFileUtils::sharedFileUtils()->getWritablePath() + pFileName; CCLog("path = %s",path.c_str()); unsigned long len = 0; //讀取文件,注意使用參數"rb",r表示read,b表示二進制binary unsigned char* data = CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "rb", &len); CCLog("read data length = %d", len); //如果以前設置找不到文件有提示,則改回原來的設置 if(isNeedModifyPopupSetting) { CCFileUtils::sharedFileUtils()->setPopupNotify(true); } return data; }
二進制文件的寫入:
bool wkFileUtils::saveFile(unsigned char *pContent, string pFileName, int length){ //獲取儲存的文件路徑 string path = CCFileUtils::sharedFileUtils()->getWritablePath() + pFileName; CCLog("save file path = %s",path.c_str()); //創建一個文件指針,注意要使用參數"wb",w表示write,b表示二進制binary,之前我使用的是"w",ios上當時沒有發現問題,但是win32上會有bug,改成"wb"就沒有問題了 FILE* file = fopen(path.c_str(), "wb"); if (file) { fwrite(pContent, sizeof(unsigned char), length, file); fclose(file); } else { CCLog("save file error."); } return false; }