首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PhysFS损坏数据的前几个字节

PhysFS损坏数据的前几个字节
EN

Stack Overflow用户
提问于 2012-11-19 02:59:12
回答 1查看 351关注 0票数 1

因此,我正在编写的这个PhysFS类似乎破坏了它读取的所有数据的前几个字符。其余的数据看起来都没问题。

下面是被调用的代码:

代码语言:javascript
复制
std::vector<uint8_t> FileIO::vectorFromFile(std::string fileName)
{
    auto buffer = std::make_shared<std::vector<uint8_t> > (*new std::vector<uint8_t>);
    if(PHYSFS_exists(fileName.c_str()))
    {
        PHYSFS_File* filenameHandle = PHYSFS_openRead(fileName.c_str());
        if (filenameHandle != 0)
        {
            bufferSize = PHYSFS_fileLength(filenameHandle);
            buffer->resize(bufferSize);
            PHYSFS_read (filenameHandle, &buffer->front(), sizeof(uint8_t), bufferSize);
            PHYSFS_close(filenameHandle);
        }
    }
    else
    {
        std::cerr << fileName << " doesn't exist.";
    }
    buffer->push_back((uint8_t) '\0');
    return *buffer;
}

SimpleFile FileIO::getSimpleFile(std::string fileName)
{
    SimpleFile file;
    std::vector<uint8_t> dataVector = vectorFromFile(fileName);
    file.data = &(dataVector[0]);
    file.sizeInBytes = dataVector.size();

    return file;
}

And this example输出:

代码语言:javascript
复制
─ s  9c rsion="1.0" encoding="UTF-8"?>
<map version="1.0" orientation="orthogonal" width="40" height="40" tilewidth="32
" tileheight="32">
 <tileset firstgid="1" name="Desert" tilewidth="32" tileheight

当它应该是:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" orientation="orthogonal" width="40" height="40" tilewidth="32"
tileheight="32">
 <tileset firstgid="1" name="Desert" tilewidth="32" tileheight

抱歉弄坏了粘贴盒。

我是一个从文件系统和PhysFS读取数据的新手,所以如果我犯了一个明显的错误,请原谅我。

编辑:标题:

代码语言:javascript
复制
#ifndef FILEIO_H
#define FILEIO_H

#include <string>
#include <vector>

struct SimpleFile;

class FileIO
{
private:
    int bufferSize = 0;
public:
    FileIO();
    ~FileIO();
    std::vector<uint8_t> vectorFromFile(std::string fileName);
    SimpleFile getSimpleFile(std::string fileName);
};

struct SimpleFile
{
    uint8_t* data;
    int sizeInBytes;
};

#endif // FILEIO_H
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-21 08:35:54

我认为您的数据正在超出范围,并被重用于其他事情:

代码语言:javascript
复制
SimpleFile FileIO::getSimpleFile(std::string fileName)
{
    SimpleFile file;
    std::vector<uint8_t> dataVector = vectorFromFile(fileName);
    file.data = &(dataVector[0]);
    file.sizeInBytes = dataVector.size();
    return file;
}

一旦函数返回,dataVector就消失了,所以file.data是一个无效的指针。当然,我不太了解可以覆盖这一点的C++11新功能。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13443456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档