[cocos2dx 3.0] 对文件读写操作 +FileUtils类

cocos2dx的文件工具类 FileUtils,用于对文件的简单操作,下面列出一些大概用得到的函数:

 static FileUtils* getInstance();//获取FileUtils类的实例

cocos2dx中有很多拥有共享实例的类,再以前版本的获取实例是用sharedXXX()函数来获取的,而3.0都只使用一个函数getInstance()来获取。可以看下面的说明:

[cpp]  view plain copy
  1. /** @deprecated Use getInstance() instead */  
  2. CC_DEPRECATED_ATTRIBUTE static FileUtils* sharedFileUtils() { return getInstance(); }  

可以看出虽然现在还可以使用sharedFileUtils(),但他已经被标注为废弃。很显然使用getInstance()更加明了简介。

std::string getStringFromFile(const std::string& filename);//读取文件中的字符串

Data getDataFromFile(const std::string& filename);//获取文件数据

下面看一下Data类

[cpp]  view plain copy
  1. class CC_DLL Data  
  2. {  
  3. public:  
  4.     static const Data Null;  
  5.     //构造函数  
  6.     Data();  
  7.     Data(const Data& other);  
  8.     Data(Data&& other);  
  9.     ~Data();  
  10.     // 重载符号  
  11.     Data& operator= (const Data& other);  
  12.     Data& operator= (Data&& other);  
  13.   
  14.     unsigned char* getBytes() const;//获取数据  
  15.     ssize_t getSize() const;//尺寸  
  16.     void copy(unsigned char* bytes, const ssize_t size);//从bytes复制  
  17.     void fastSet(unsigned char* bytes, const ssize_t size);//从bytes快速set,使用后bytes将不能在外部使用  
  18.     void clear();//清除  
  19.     bool isNull() const;//判空  
  20. private:  
  21.     void move(Data& other);  
  22. private:  
  23.     unsigned char* _bytes;  
  24.     ssize_t _size;  
  25. };  

unsigned char* getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size);//读取压缩文件数据(zip格式)

如果读取成功size中会返回文件的大小,否则返回0。

std::string fullPathForFilename(const std::string &filename);//获取文件的完整路径

如果我们通过setSearchPaths()设置搜索路径("/mnt/sdcard/", "internal_dir/"),然后通过setSearchResolutionsOrder()设置子区分路径("resources-ipadhd/", "resources-ipad/", "resources-iphonehd")。如果搜索文件名为'sprite.png' 那么会先在文件查找字典中查找key: sprite.png -> value: sprite.pvr.gz,然后搜索文件'sprite.pvr.gz'如下顺序:

[html]  view plain copy
  1. /mnt/sdcard/resources-ipadhd/sprite.pvr.gz      (if not found, search next)  
  2. /mnt/sdcard/resources-ipad/sprite.pvr.gz        (if not found, search next)  
  3. /mnt/sdcard/resources-iphonehd/sprite.pvr.gz    (if not found, search next)  
  4. /mnt/sdcard/sprite.pvr.gz                       (if not found, search next)  
  5. internal_dir/resources-ipadhd/sprite.pvr.gz     (if not found, search next)  
  6. internal_dir/resources-ipad/sprite.pvr.gz       (if not found, search next)  
  7. internal_dir/resources-iphonehd/sprite.pvr.gz   (if not found, search next)  
  8. internal_dir/sprite.pvr.gz                      (if not found, return "sprite.png")  

如果找到返回完整路径,没找到返回'sprite.png'。

void loadFilenameLookupDictionaryFromFile(const std::string &filename);//从文件导入文件名查找字典

文件为plist格式如下:

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">  
  3. <plist version="1.0">  
  4. <dict>  
  5.     <key>filenames</key>  
  6.     <dict>  
  7.         <key>sounds/click.wav</key>  
  8.         <string>sounds/click.caf</string>  
  9.         <key>sounds/endgame.wav</key>  
  10.         <string>sounds/endgame.caf</string>  
  11.         <key>sounds/gem-0.wav</key>  
  12.         <string>sounds/gem-0.caf</string>  
  13.     </dict>  
  14.     <key>metadata</key>  
  15.     <dict>  
  16.         <key>version</key>  
  17.         <integer>1</integer>  
  18.     </dict>  
  19. </dict>  
  20. </plist>  

key对应string

void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);//从ValueMap中设置文件名查找字典

ValueMap的定义:

[cpp]  view plain copy
  1. typedef std::unordered_map<std::string, Value> ValueMap;  

std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile);//获取相对应文件的完整路径 

e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist   Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. )

void setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder);//设置子搜索区分路径

见fullPathForFilename()。

void addSearchResolutionsOrder(const std::string &order);//增加子搜索路径

const std::vector<std::string>& getSearchResolutionsOrder();//获取子搜索区分路径

void setSearchPaths(const std::vector<std::string>& searchPaths);//设置搜索路径

见fullPathForFilename()。

void addSearchPath(const std::string & path);//增加搜索路径

const std::vector<std::string>& getSearchPaths() const;//获取搜索路径

std::string getWritablePath();//获取一个可写入文件的路径

经过测试在win32平台上,debug版本返回的是程序文件所在的路径,release返回的是“我的文档”路径。

bool isFileExist(const std::string& filePath);//判断文件是否存在

经过测试在win32平台上,如果路径中包含中文字符会找不到文件。所以可以自己写个

[cpp]  view plain copy
  1. bool wFileIO::isFileExist(const std::string& pFileName)  
  2. {  
  3. #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)  
  4.     return CCFileUtils::getInstance()->isFileExist(pFileName);  
  5. #else  
  6.     if(GetFileAttributesA(pFileName.c_str()) == INVALID_FILE_ATTRIBUTES)  
  7.         return false;  
  8.     return true;  
  9. #endif  
  10. }  

bool isAbsolutePath(const std::string& path);判断是否为绝对路径


void setPopupNotify(bool notify);

bool isPopupNotify();

Sets/Gets 当文件加载失败时弹出messagebox.

ValueMap getValueMapFromFile(const std::string& filename);//从文件获取ValueMap

bool writeToFile(ValueMap& dict, const std::string& fullPath);//写入一个ValueMap数据到plist格式文件

ValueVector getValueVectorFromFile(const std::string& filename);//从文件获取ValueVector

ValueVector定义:

[cpp]  view plain copy
  1. typedef std::vector<Value> ValueVector;  
函数就这么多了,就在这里记录下,到时要用再来看看 奋斗
因为没发现有直接写文件的函数,所以我这里自己写了下,虽然不知道再其他平台会怎样,再windows上用着再说 大笑
再win32上realse版本getWritablePath()会获取“我的文档”,还是改成当前路径吧
[cpp]  view plain copy
  1. std::string wFileIO::getWritablePath()  
  2. {  
  3. #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)  
  4.     return CCFileUtils::getInstance()->getWritablePath();  
  5. #else  
  6.     char full_path[MAX_PATH + 1];  
  7.     ::GetModuleFileNameA(NULL, full_path,MAX_PATH + 1);  
  8.     std::string ret((char*)full_path);  
  9.     // remove xxx.exe  
  10.     ret =  ret.substr(0, ret.rfind("\\") + 1);  
  11.     ret = convertPathFormatToUnixStyle(ret);  
  12.     return ret;  
  13. #endif  
  14. }  
下面是保存文件:
[cpp]  view plain copy
  1. bool wFileIO::saveFile(const char* pContentString, const std::string& pFileName)  
  2. {  
  3.     std::string fn=convertPathFormatToUnixStyle(pFileName);  
  4.     int np=fn.rfind('/');  
  5.     if(np!=std::string::npos)  
  6.         if(!mkDirM(fn.substr(0,np)))  
  7.             return false;  
  8.   
  9.     std::string path = getWritablePath()+fn;  
  10.     FILE* file = fopen(path.c_str(), "w");    
  11.     if (file)  
  12.     {    
  13.         fputs(pContentString, file);    
  14.         fclose(file);   
  15.         log("save file [%s]",path.c_str());    
  16.         return true;  
  17.     }  
  18.     else  
  19.         log("fail to save file [%s]!",path.c_str());  
  20.     return false;  
  21. }  
  22. //检测各级文件夹,不存在则创建  
  23. bool wFileIO::mkDirM(const std::string& pDirName)  
  24. {  
  25.     std::string path = getWritablePath();  
  26.     int np=pDirName.find('/',0);  
  27.     while(np!=std::string::npos)  
  28.     {  
  29.         if(!mkDir(path+pDirName.substr(0,np)))  
  30.             return false;  
  31.         np=pDirName.find('/',np+1);  
  32.     }  
  33.     return mkDir(path+pDirName);  
  34. }  
  35.   
  36. //创建文件夹  
  37. bool wFileIO::mkDir(const std::string& pDirName)  
  38. {  
  39. #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)  
  40.     DIR *pDir = NULL;  
  41.     //打开该路径  
  42.     pDir = opendir (pDirName.c_str());  
  43.     if (! pDir)  
  44.     {  
  45.     //创建该路径  
  46.         if(!mkdir(pDirName.c_str(), S_IRWXU | S_IRWXG | S_IRWXO))  
  47.         {  
  48.             log("fail to create dir [%s]",pDirName.c_str());  
  49.             return false;  
  50.         }  
  51.         log("create dir [%s]",pDirName.c_str());  
  52.     }  
  53. #else  
  54.     if ((GetFileAttributesA(pDirName.c_str())) == INVALID_FILE_ATTRIBUTES)  
  55.     {  
  56.         if(!CreateDirectoryA(pDirName.c_str(), 0))  
  57.         {  
  58.             log("fail to create dir [%s]",pDirName.c_str());  
  59.             return false;  
  60.         }  
  61.         log("create dir [%s]",pDirName.c_str());  
  62.     }  
  63. #endif  
  64.       
  65.     return true;  
  66. }  
  67. //路径格式转为UnixStyle,"c:\xxx.txt" --> "c:/xxx.txt"  
  68.     static inline std::string convertPathFormatToUnixStyle(const std::string& path)  
  69.     {   
  70.         std::string ret = path; int len = ret.length();  
  71.         for (int i = 0; i < len; ++i)   
  72.         {   
  73.             if (ret[i] == '\\')   
  74.             {   
  75.                 ret[i] = '/';   
  76.             }   
  77.         }   
  78.         return ret;  
  79.     }  
  80.       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值