转载自http://blog.csdn.net/chiuan/article/details/8618411
有所修改。
为了保存自定义数据文件,需要保存文件和读取文件,即file的io操作。下面简单介绍file的io操作
针对cocos2d-x来说,我们可以使用
std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();获得一个可读取写入的文件路径,在ios上得到的是~/Library/Application Support/iPhone Simulator/5.0/Applications/....../Documents/路径。沙盒里面的documents路径。
关于file我们要明白几个概念
FiLE:文件对象,用于创建文件,操作文件。
fopen(文件路径, 文件模式) : 打开文件。模式是指 写,读权限“w”\“r”
fseek() 移动文件指针
ftell() 得到文件指针的位置,
rewind() 文件指针重置。
malloc() 分配内存空间。
fread() 把一个文件内容读到buff存储空间, 单位大小,长度, 文件指针
fputs() 把内容写进一个文件。
下面是源代码 保存和读取类
//
// DuFileUtils.h
// SpaceShooter
//
// Created by 杜宏量 on 8/27/13.
//
//
#ifndef __SpaceShooter__DuFileUtils__
#define __SpaceShooter__DuFileUtils__
#include <iostream>
#include "cocos2d.h"
USING_NS_CC;
using namespace std;
class DuFileUtils {
public:
/** 读取本地文件,返回数据 */
static string getFileByName(string sFileName);
/** 储存内容到文件 */
static bool saveFile(char* pContent, string sFileName);
};
#endif /* defined(__SpaceShooter__DuFileUtils__) */
cpp实现类
//
// DuFileUtils.cpp
// SpaceShooter
//
// Created by 杜宏量 on 8/27/13.
//
//
#include "DuFileUtils.h"
string DuFileUtils::getFileByName(string sFileName)
{
string path = CCFileUtils::sharedFileUtils()->getWritablePath() + sFileName;
CCLog("read path = %s", path.c_str());
FILE *file = fopen(path.c_str(), "r");
if (file) {
char *buff;
int len;
fseek(file, 0, SEEK_END); // 移到文件尾部
len = ftell(file); // 获取文件长度
rewind(file); // 回归原位
CCLog("file lenth = %d", len);
buff = (char *)malloc(sizeof(char) * len + 1);
if (!buff) {
CCLog("malloc space is not enough");
return NULL;
}
// 读到buff, 单位字符大小, 长度, 文件指针。
int rLen = fread(buff, sizeof(char), len, file);
buff[rLen] = '\0';
CCLog("has read lengh %d", rLen);
CCLog("has read content %s", buff);
string content = buff;
fclose(file);
free(buff);
return content;
}
else {
CCLog("open file error");
}
return NULL;
}
bool DuFileUtils::saveFile(char *pContent, string sFileName)
{
bool success = false;
if (!sFileName.c_str() || !pContent) {
return success;
}
string path = CCFileUtils::sharedFileUtils()->getWritablePath() + sFileName;
CCLog("write path = %s", path.c_str());
FILE* file = fopen(path.c_str(), "w");
if (file) {
fputs(pContent, file);
fclose(file);
success = true;
}
else {
CCLog("write file error");
}
return success;
}