cocos2d-x 数据存储 CCFileUtils

本文介绍了如何在cocos2d-x项目中利用CCFileUtils工具类进行数据的读取和保存,包括读取文件内容的方法和写入文件的实现,以及实际的存取示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 、工具类头文件

#ifndef __TDInvFileUtils__
#define __TDInvFileUtils__


#include <iostream>
#include "cocos2d.h"
using namespace cocos2d;
using namespace std;
class TdInvFileUtils
{
public:
    //读取内容
    static string getFileContentByName(string name);
    //写入内容
    static bool saveContent(char* content,
                            string name);
};
#endif

2、工具类实现

#include "TdInvFileUtils.h"
#include <iostream>
#include "cocos2d.h"
#include <iostream>
using namespace cocos2d;
using namespace std;


string TdInvFileUtils::getFileContentByName(
    string name)
{
    //使用CCFileUtils获得文件内容
    string path =
        CCFileUtils::sharedFileUtils()->getWritablePath()
        +name;
    // CCLog("read contate form path=%s",path);
    //使用只读方式打开文件
    FILE* file = fopen(path.c_str(),"r");
    if(file)
    {
        char* buffer;//要读取的字符串
        int len;//读取长度
        //获得长度,指针移到尾部,读取长度,指针归位
        fseek(file,0,SEEK_END);
        len = ftell(file);
        rewind(file);
        //分配内存
        buffer = (char*)malloc(sizeof(char)*len+1);
        int lenEnd = fread(buffer,sizeof(char),len,file);
        buffer[lenEnd]='\0';//文件结尾
        string result = buffer;
        fclose(file);//关闭文件
        free(buffer);//释放空间
        //    CCLog("read success and content = %s",result);
        return result;
    }
    else
    {
        CCLog("open file %s error",path);
        return NULL;
    }
}


bool TdInvFileUtils::saveContent(char* content,
                                 string name)
{
    string path =
        CCFileUtils::sharedFileUtils()->getWritablePath()
        +name;
    FILE* file = fopen(path.c_str(),"w");
    if(file)
    {
        //写入内容
        fputs(content,file);
        fclose(file);
        return true;
    }
    else
    {
        CCLog("write file error");
        return false;
    }
}

3、存取

 //采用文件的方式存取数据,CCFileUtils
    char content[200]= {""};
    sprintf(content,
            "Best Score is %d , and new Score is %d",
            bestScore,score);
    TdInvFileUtils::saveContent(content,"scoreFile");

 //从文件中读取数据
    string result =
        TdInvFileUtils::getFileContentByName("scoreFile");
    CCLog(result.c_str());


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值