在公司在项目开发的时候需要读取本地的文件,于是在网上搜索了一下以下关于Cocos2d-x文件读取的操作,用了两种方法都可以实现,一种是使用C++另种是Cocos2d-x代码如下:
//读取文件(参数分别为文件名和文本框)
void GameRegistry::readFile(const char *pFileName,UILabel *pLabel)
{
/*方法一
ifstream inFile;
inFile.open(pFileName);//打开文件
string pSaveStr;//用于保存读取一行的文件内容
for (string str;getline(inFile,str);)//一行行的读取
{
GBKToUTF8(str,"gbk","utf-8"); //中文转码,这个也是借鉴网上的
pSaveStr += str + "\n";
}
//设置文本框内容
pLabel->setText(pSaveStr);
pLabel->setFontName("微软雅黑");
//关闭文件
inFile.close();
*/
//方法二
//获取文件在系统的绝对路径
string filePath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFileName);
//读取的内容
unsigned char *data = NULL;
//读取的字节数,读取失败则为0
unsigned long len = 0;
data = CCFileUtils::sharedFileUtils()->getFileData(filePath.c_str(),"r",&len);
//unsigned char* 转 sting
std::string my_std_string(reinterpret_cast<const char *>(data),len);
//中文转码
GBKToUTF8(my_std_string,"gbk","utf-8");
pLabel->setText(my_std_string);
pLabel->setFontName("微软雅黑");
//释放内存
if (len>0&&data)
{
delete[] data;
}
}Cocos2d-x读取本地文件,布布扣,bubuko.com
Cocos2d-x读取本地文件
原文:http://blog.csdn.net/wcluojiji/article/details/38514261