[cocos2d-x]File文件的IO读写处理
转自:
为了保存自定义数据文件,需要保存文件和读取文件,也就是File的IO处理; 针对cocos2d-x我们可以通过CCFileUtils::sharedFileUtils()->getWriteablePath()获取到可读写的文件目录,其实是Caches目录。 关于file的操作,我们要明白几个概念: File :文件对象,用于创建文件,操作文件 fopen:打开操作一个具体文件(文件路径,模式)模式有"w""r"读写等 fseek:移动文件指针 ftell:得到文件指针的位置,距离开头 rewind:文件指针重置 malloc:分配内存空间 fread:读一个文件的内容,需要输入buf储存空间,单位大小,长度,文件指针 fputs:写内容进去一个文件 摘录读取模式 r以只读方式打开文件,该文件必须存在。 以下是代码,2个静态方法,保存和读取:TDInvFileUtils.h // // TDInvFileUtils.h // MyCocoa2DTest // // Created by 韦 柱全 on 13-2-27. // // #ifndef __MyCocoa2DTest__TDInvFileUtils__ #define __MyCocoa2DTest__TDInvFileUtils__ #include <iostream> #include "cocos2d.h" using namespace cocos2d; using namespace std; /** 负责操作文件储存和读取 */ class TDInvFileUtils { public: /** 读取本地文件,返回数据 */ static string getFileByName(string pFileName); /** 储存内容到文件 */ static bool saveFile(char* pContent,string pFileName); }; #endif /* defined(__MyCocoa2DTest__TDInvFileUtils__) */ 其实现文件 TDInvFileUtils.cpp // // TDInvFileUtils.cpp // MyCocoa2DTest // // Created by 韦 柱全 on 13-2-27. // // #include "TDInvFileUtils.h" string TDInvFileUtils::getFileByName(string pFileName){ //第一先获取文件的路径 string path = CCFileUtils::sharedFileUtils()->getWriteablePath() + pFileName; CCLOG("path = %s",path.c_str()); //创建一个文件指针 FILE* file = fopen(path.c_str(),"r"); if (file) { char* buf; //要获取的字符串 int len; //获取的长度 /*获取长度*/ fseek(file,SEEK_END); //移到尾部 len = ftell(file); //提取长度 rewind(file); //回归原位 CCLOG("count the file content len = %d",len); //分配buf空间 buf = (char*)malloc(sizeof(char) * len + 1); if (!buf) { CCLOG("malloc space is not enough."); return NULL; } //读取文件 //读取进的buf,单位大小,长度,文件指针 int rLen = fread(buf,sizeof(char),len,file); buf[rLen] = ' '; CCLOG("has read Length = %d",rLen); CCLOG("has read content = %s",buf); string result = buf; fclose(file); free(buf); return result; } else CCLOG("open file error."); return NULL; } bool TDInvFileUtils::saveFile(char *pContent,string pFileName){ //第一获取储存的文件路径 string path = CCFileUtils::sharedFileUtils()->getWriteablePath() + pFileName; CCLOG("wanna save file path = %s",path.c_str()); //创建一个文件指针 //路径、模式 FILE* file = fopen(path.c_str(),"w"); if (file) { fputs(pContent,file); fclose(file); } else CCLOG("save file error."); return false; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |