Cocos2dx 读写文件,首选项


(一)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)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值