cocos2d-x -----文件的读取

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.");
            }
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值