1

因此,我正在编写的这个 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;
}

这个例子输出:

─ 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
4

1 回答 1

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 新特性知之甚少。

于 2012-11-21T00:35:53.957 回答