1.使用FileUtils来访问文件
FileUtils::getInstance()获取实例
2.大概使用函数:
purgeCachedEntries() 清空路径缓存
getSearchPaths() 获得搜索路径
setSearchPaths() 设置搜索路径
fullPathForFilename() 获取文件的完整路径(绝对路径)
isFileExist() 判断文件是否存在
getWritablePath() 获取可写路径
getDataFromFile() 根据文件获取文件内容的二进制数据
getStringFromFile() 根据文件获取文件字符串内容
void HelloWorld::menuOneCallback(cocos2d::Ref *pSender){
auto menu=(MenuItem*)pSender;
auto num=menu->getTag();
// 获取实例
auto shareFileUtils=FileUtils::getInstance();
if(num==5){
//清空路径缓存
shareFileUtils->purgeCachedEntries();
//获取搜索路径
std::vector<std::string> searchPaths=shareFileUtils->getSearchPaths();
//
std::string writablePath=shareFileUtils->getWritablePath();
searchPaths.insert(searchPaths.begin(), "dir");
searchPaths.insert(searchPaths.begin()+1, writablePath);
// searchPaths.insert(...,... );
// 设置搜索路径
shareFileUtils->setSearchPaths(searchPaths);
}
if(num==1){
//获取文件的完整路径(绝对路径)
std::string FullPathForName=shareFileUtils->fullPathForFilename("text.txt");
log("FullPathForName= %s",FullPathForName.c_str());
//判断是否存在文件
bool isExit=shareFileUtils->isFileExist("text.txt");
log("text.txt 是否处在: %d",isExit);
}
if (num==2) {
//获取可写路径
std::string writablePath=shareFileUtils->getWritablePath();
log("wirtablePath=%s",writablePath.c_str());
}
if (num==3) {
//1
//根据文件获取文件内容的二进制数据
Data data=shareFileUtils->getDataFromFile("text.txt");
std::string content1=std::string((const char*)data.getBytes(),0,data.getSize());
log("content1= %s",content1.c_str());
//2
//根据文件获取文件字符串内容
std::string content2=shareFileUtils->getStringFromFile("text.txt");
log("content2=%s",content2.c_str());
}
if (num==4) {
std::string writablePath=shareFileUtils->getWritablePath();
log("writablePath=%s",writablePath.c_str());
std::string fileName=writablePath+"text.txt";
char word[100]="Testing Write to file.";
//打开文件
FILE * fp =fopen(fileName.c_str(), "wb");
if(fp){
//输入内容
size_t ret=fwrite(word, 1, strlen(word), fp);;
fclose(fp);
if(ret!=0){
log("Write file to Succeed.");
}
}
}
}