(一)cpp写文件
AppDelegate::AppDelegate()
{
cocos2d::FileUtils* fu = FileUtils::getInstance();
std::string path = fu->getWritablePath();
//c++字符串转c字符串
CCLOG("writable path is %s\n", path.c_str());
//写入文件
std::string txtFilePath = fu->fullPathFromRelativeFile("leason01.txt", path);
CCLOG("file path is %s\n", txtFilePath.c_str());
FILE * file = fopen(txtFilePath.c_str(), "w");
char * fileContent = "Hello World!\0";
fwrite(fileContent, 1, strlen(fileContent), file);
fclose(file);
}
cocos2d::FileUtils* fu = FileUtils::getInstance();
std::string path = fu->getWritablePath();
//c++字符串转c字符串
CCLOG("writable path is %s\n", path.c_str());
//写入文件
std::string txtFilePath = fu->fullPathFromRelativeFile("leason01.txt", path);
CCLOG("file path is %s\n", txtFilePath.c_str());
fu->writeStringToFile("Hello leason01\n", txtFilePath);
(二)cpp读文件
/*
FILE *file = fopen(txtFilePath.c_str(), "r");
char* buffer = new char[1024];
memset(buffer, 0, 1024);
int readLen = fread(buffer, 1, 1024, file);
fclose(file);
CCLOG("read len is %d, string data is %s \n", readLen, buffer);
delete(buffer);
*/
std::string readString = fu->getStringFromFile(txtFilePath);
CCLOG("read string is %s", readString.c_str());
(三) lua读写文件
--读写文件
local function readFileTest()
local fu = cc.FileUtils:getInstance()
--这个路径为毛和cpp中取得 的路径不一样呢
local path = fu:getWritablePath();
print(string.format("writable path is %s", path))
local filePath = fu:fullPathFromRelativeFile("leason02.txt", path)
--能使用io库
local file = io.open(filePath, "w")
if file ~= nil then
file:write("Hello Leason02")
file:close()
print("write successfully..")
end
end
(四),读写首选项文件
cocos2d在可写根路径中创建了UserDefault.xml文件,存放一些数据,例如背景音乐音效的开关状态,用户名等等,使用UserDefault类操作
local ud = cc.UserDefault:getInstance()
local isExist = cc.UserDefault:isXMLFileExist()
print("isExist is ", isExist)
--ud:setStringForKey("key1", "value1")
--ud:flush()
print("data is ", ud:getStringForKey("key1", "no data"))
local userDefaultFilePath = cc.UserDefault:getXMLFilePath()
print("userDefaultFilePath=", userDefaultFilePath)
isExist = cc.UserDefault:isXMLFileExist()
print("isExist is ", isExist)