升级引擎cocos_lua 3.10升级到3.17,FileUtil中getData()函数被getContents()取代,搞不懂新版getContents()函数参数ResizableBuffer*类型的用法。因为需要做资源加密,目前对应两者文件读取的区别不是很明白

3.10旧版代码:

static Data getData(const std::string& filename, bool forString)
{
if (filename.empty())
{
return Data::Null;
}

Data ret;
unsigned char* buffer = nullptr;
size_t size = 0;
size_t readsize;
const char* mode = nullptr;

if (forString)
    mode = "rt";
else
    mode = "rb";

auto fileutils = FileUtils::getInstance();
do
{
    // Read the file from hardware
    std::string fullPath = fileutils->fullPathForFilename(filename);

    FILE *fp = fopen(fileutils->getSuitableFOpen(fullPath).c_str(), mode);
    CC_BREAK_IF(!fp);
    fseek(fp,0,SEEK_END);
    size = ftell(fp);
    fseek(fp,0,SEEK_SET);

    if (forString)
    {
        buffer = (unsigned char*)malloc(sizeof(unsigned char) * (size + 1));
        buffer[size] = '\0';
    }
    else
    {
        buffer = (unsigned char*)malloc(sizeof(unsigned char) * size);
    }

    readsize = fread(buffer, sizeof(unsigned char), size, fp);
    fclose(fp);

    if (forString && readsize < size)
    {
        buffer[readsize] = '\0';
    }


} while (0);

if (nullptr == buffer || 0 == readsize)
{
    CCLOG("Get data from file %s failed", filename.c_str());
}
else
{
    ret.fastSet(buffer, readsize);
}

return ret;

}

3.17.2新版代码

FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableBuffer* buffer) const
{
if (filename.empty())
return Status::NotExists;

auto fs = FileUtils::getInstance();

std::string fullPath = fs->fullPathForFilename(filename);


if (fullPath.empty())
    return Status::NotExists;

std::string suitableFullPath = fs->getSuitableFOpen(fullPath);

struct stat statBuf;
if (stat(suitableFullPath.c_str(), &statBuf) == -1) {
    return Status::ReadFailed;
}

if (!(statBuf.st_mode & S_IFREG)) { 
    return Status::NotRegularFileType;
}

FILE *fp = fopen(suitableFullPath.c_str(), "rb");
if (!fp)
    return Status::OpenFailed;

size_t size = statBuf.st_size;

buffer->resize(size);
size_t readsize = fread(buffer->buffer(), 1, size, fp);
fclose(fp);  


if (readsize < size) {
    buffer->resize(readsize);
    return Status::ReadFailed;
}

return Status::OK;

}

有注释,第三个用法 Data 参数,不就是老版本中的 Data 返回值

    /**
     *  Gets whole file contents as string from a file.
     *
     *  Unlike getStringFromFile, these getContents methods:
     *      - read file in binary mode (does not convert CRLF to LF).
     *      - does not truncate the string when '\0' is found (returned string of getContents may have '\0' in the middle.).
     *
     *  The template version of can accept cocos2d::Data, std::basic_string and std::vector.
     *
     *  @code
     *  std::string sbuf;
     *  FileUtils::getInstance()->getContents("path/to/file", &sbuf);
     *
     *  std::vector<int> vbuf;
     *  FileUtils::getInstance()->getContents("path/to/file", &vbuf);
     *
     *  Data dbuf;
     *  FileUtils::getInstance()->getContents("path/to/file", &dbuf);