Search code examples
androidc++cocos2d-xassets

cocos2d-x & android loading files from the assets folder


I have a bunch of plist files in the assets/plist/ folder and I am trying to load these files to validate their hashes.

what happens is that the following code fails for me

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

The returned char array is always empty.

Trying to open the same file with fopen also results in a null pointer for the file handle.

I have verified that the full path is assets/plists/file.plist and that the file.plist exists in the assets/plist folder.

What am I doing wrong here?


Solution

  • FileUtils->getInstance()->getFileData was the way for me to go as well for reading asset resources. I wrapped this in a utility function when reading text files:

        #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;
            }
        }