【问题标题】:cocos2d-x & android loading files from the assets foldercocos2d-x & android 从 assets 文件夹加载文件
【发布时间】:2014-04-10 08:00:57
【问题描述】:

我在 assets/plist/ 文件夹中有一堆 plist 文件,我正在尝试加载这些文件以验证它们的哈希值。

发生的事情是以下代码对我来说失败了

const char *fullPath = cocos2d::CCFileUtils::sharedFileUtils()->fullPathForFilename(name).c_str();
std::ifstream ifs(fullPath, std::ios::binary);
std::vector<char> str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());

返回的 char 数组始终为空。

尝试使用 fopen 打开同一个文件也会导致文件句柄的空指针。

我已验证完整路径为assets/plists/file.plist,并且file.plist 存在于assets/plist 文件夹中。

我在这里做错了什么?

【问题讨论】:

  • 这些东西在部署到 Android 时不会被压缩和打包吗?我认为您可能需要通过 Java 获取句柄并将其传递回 C++,因为它具有将其从 zip 文件中取出的逻辑(我知道......它很烂......)
  • 更多信息请见this question
  • 感谢 borrrden 指出真正的错误。

标签: android c++ cocos2d-x assets


【解决方案1】:

感谢 borrrden 的参考。你提到的那个问题并没有完全回答我的问题,而是让我想到了这个。

对于那些偶然发现这个问题的人,资产文件夹被压缩在 APK 中,与 iOS 不同的是,它无法直接从那里读取文件。对于适用于 iOS 和 Android 以及 Assets 中的文件夹以及其他方面的一致解决方案,下面的代码使用 cocos2d-x 框架中的 CCFileUtils 来读取文件。

unsigned long pSize = 0;
unsigned char* str = CCFileUtils::sharedFileUtils()->getFileData(name, "rb", &pSize);
std::string hash = GCGameUtils::sharedInstance()->hmacForKeyAndData(str, name, pSize);
delete[] str;

cocos2d-x fileutils 已经有了这个很酷的功能来获取文件数据!

【讨论】:

  • 什么是GCGameUtils?是你自己的图书馆吗?谷歌不知道:)
  • 哦,对不起。 GCGameUtils 是我自己的库。我用它来加密和保护文件的内容。
【解决方案2】:

FileUtils->getInstance()->getFileData 也是我阅读资产资源的方式。我在读取文本文件时将其包装在一个实用函数中:

    #include "cocos2d.h"
    #include <iosfwd>
    #include <sstream>
    #include <memory>

    namespace FileUtil
    {
        using ResourceStream = std::basic_istringstream<char>;

        bool readResourceFile(std::shared_ptr<ResourceStream>& stream,const std::string& filename);

        bool readResourceFile(std::shared_ptr<ResourceStream>& stream,const std::string& filename)
        {
            // Note: Returned data allocated by "malloc" so must free when copy to string stream

            CCLOG("FileUtil::readResourceFile - Attempting to read resource file %s",filename.c_str());

            ssize_t size = 0;
            char* data = reinterpret_cast<char*>(FileUtils::getInstance()->getFileData(filename, "r", &size));
            if(!data || size == 0)
            {
                CCLOG("FileUtil::readResourceFile - unable to read filename %s - size was %lu",filename.c_str(),size);
                if(data)
                {
                    free(data);
                }
                return false;
            }

            CCLOG("FileUtil::readResourceFile - Read %lu bytes from resource file %s",size,filename.c_str());

            std::string stringData(data);
            // release since we've copied to string
            free(data);

            stream.reset(new std::istringstream(stringData));

            return true;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-21
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2011-02-21
    • 1970-01-01
    相关资源
    最近更新 更多