1. 程式人生 > >【儲存】Cocos2d-x將資源目錄(Assets)檔案拷貝到可寫目錄

【儲存】Cocos2d-x將資源目錄(Assets)檔案拷貝到可寫目錄

【說明】

將安卓的資源目錄(Assets)下得指定檔案,拷貝到可寫目錄指定位置,以便對檔案進行讀寫。

【正文】

1. 首先得在可寫目錄建立指定的資料夾,當然也可以不用,如果建立目錄,則需包含標頭檔案。

#include <sys/stat.h>
#include <dirent.h>
bool FileHelper::createDirectory(const std::string& dirpath)
{
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
    DIR *pDir = opendir(dirpath.c_str()); // 開啟目錄
    if (!pDir)
    {
        // 建立目錄
        int ret = mkdir(dirpath.c_str(), S_IRWXU|S_IRWXG|S_IRWXO);
        if (ret != 0 && errno != EEXIST)
        {
            return false;
        }
    }
    return true;
#else
    if ((GetFileAttributesA(dirpath.c_str())) == INVALID_FILE_ATTRIBUTES)
    {
        BOOL ret = CreateDirectoryA(dirpath.c_str(), NULL);
        if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
        {
            return false;
        }
    }
    return true;
#endif
}
2. 拷貝檔案,此處封裝的資源目錄相對路徑和可寫目錄相對路徑是一樣的,所以都用filename包含相對路徑。
bool FileHelper::copyFile(const std::string& filename)
{
    // 資源路徑
    std::string sourcePath = FileUtils::getInstance()->fullPathForFilename(filename);
    Data data = FileUtils::getInstance()->getDataFromFile(sourcePath);
    
    // 可寫路徑
    std::string destPath = FileUtils::getInstance()->getWritablePath() + filename;
    FILE *fp = fopen(destPath.c_str(), "w+");
    if (fp)
    {
        size_t size = fwrite(data.getBytes(), sizeof(unsigned char), data.getSize(), fp);
        fclose(fp);
        
        if (size > 0)
        {
            return true;
        }
    }
    CCLOG("copy file %s failed.", filename.c_str());
    return false;
}
3. 使用
// 檢查目錄(如果不存在將建立目錄)
std::string writablePath = FileUtils::getInstance()->getWritablePath();
FileHelper::createDirectory(writablePath + "config/");
    
// 拷貝檔案(從資源目錄拷貝到可寫目錄)
FileHelper::copyFile("config/data.db");