PhysFS破坏了前几个字节的数据

时间:2012-11-18 18:59:12

标签: c++ physfs

因此,我正在编写的这个PhysFS类似乎正在破坏它读取的所有数据的前几个字符。其余的数据似乎很好......

以下是被调用的代码:

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输出:

─ 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

应该是:

<?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

对于pastebin感到抱歉。

我从文件系统和PhysFS读取时有点新鲜,所以如果我犯了一个明显的错误,请原谅我。

编辑: 标题:

#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

1 个答案:

答案 0 :(得分:1)

我认为您的数据超出范围并被重用于其他内容:

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可以覆盖它的新功能知之甚少。