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