cocos2d-x 3.2文件读写普通文件,plist,xml

一.普通文件读写

1.写入文件(bool HelloWorld::init()里写入如下代码)

   FileUtils *fu=FileUtils::getInstance();
    FILE *f=fopen(fu->fullPathFromRelativeFile("data.txt",fu->getWritablePath()).c_str(),"w");
    fprintf(f,"Hello ws\n");
    fclose(f);
    log("%s",fu->getWritablePath().c_str());

2.读取文件
    Data d=fu->getDataFromFile(fu->fullPathFromRelativeFile("data.txt",fu->getWritablePath()));
    log("%s",d.getBytes());

3.UserDefault的用法
    UserDefault::getInstance()->setStringForKey("data","Hello ws");
    
    log("%s",UserDefault::getInstance()->getStringForKey("data1","Hello world").c_str());


二.读取plist文件

1.先在resource里创建plist文件


2.然后在HelloWorldScene.cpp的init()函数输入以下代码即可

    FileUtils *fu=FileUtils::getInstance();
    auto vm=fu->getValueMapFromFile("data.plist");//dictionary,如果是vector,使用fu->getValueVectorFromFile(const std::string &filename)
    
    log("%s",vm["name"].asString().c_str());
    log("%s",vm["arr"].asValueVector().at(1).asString().c_str());

三.读取xml文件

1.先在resource里创建xml文件,在里面输入

<data>
    <p name="ZhangSan" age="10" />
    <p name="LiSi" age="11" />
</data>

2.输入以下代码
  auto doc =new tinyxml2::XMLDocument();
    doc->Parse(FileUtils::getInstance()->getStringFromFile("data.xml").c_str());
    
    auto root=doc->RootElement();
    for (auto e=root->FirstChildElement(); e; e=e->NextSiblingElement()) {
        std::string str;
        for (auto attr=e->FirstAttribute(); attr; attr=attr->Next()) {
            str+=attr->Name();
            str+=":";
            str+=attr->Value();
            str+=",";
        }
        log("%s",str.c_str());
    }

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...