转载:http://blog.****.net/chiuan/article/details/8618411
为了保存自定义数据文件,需要保存文件和读取文件,也就是File的IO处理;
针对cocos2d-x我们可以通过CCFileUtils::sharedFileUtils()->getWriteablePath()获取到可读写的文件目录,其实是Caches目录。
关于file的操作,我们要明白几个概念:
File :文件对象,用于创建文件,操作文件
fopen:打开操作一个具体文件(文件路径,模式)模式有"w"\"r"读写等
fseek:移动文件指针
ftell:得到文件指针的位置,距离开头
rewind:文件指针重置
malloc:分配内存空间
fread:读一个文件的内容,需要输入buf储存空间,单位大小,长度,文件指针
fputs:写内容进去一个文件
摘录读取模式
r 以只读方式打开文件,该文件必须存在。
r+ 以可读写方式打开文件,该文件必须存在。
rb+ 读写打开一个二进制文件,允许读数据。
rt+ 读写打开一个文本文件,允许读和写。
w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保 留。(EOF符保留)
a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 (原来的EOF符不保留)
wb 只写打开或新建一个二进制文件;只允许写数据。
wb+ 读写打开或建立一个二进制文件,允许读和写。
wt+ 读写打开或着建立一个文本文件;允许读写。
at+ 读写打开一个文本文件,允许读或在文本末追加数据。
ab+ 读写打开一个二进制文件,允许读或在文件末追加数据。
以下是代码,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, 0, 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] = '\0';
- 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;
- }