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());