cocos2d-x 文件读取与存储

转载自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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值