您的位置:首页 > 移动开发 > Cocos引擎

【存储】Cocos2d-x将资源目录(Assets)文件拷贝到可写目录

2015-08-19 14:41 549 查看
【说明】

将安卓的资源目录(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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: