【說明】
将安卓的資源目錄(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");