TheBeardless
TheBeardless

Reputation: 67

Reading from a file in C++ outputs weird characters

beginner here.

I just wrote some simple code to read a file and it is (sort of) working:
BUT: No matter what I do, I get "²" at the end of my output.

Here´s my file reading code:

std::string MSEshaderprogram::readFile(const std::string& filepath)
    {

        std::ifstream file{ filepath, std::ios::ate | std::ios::binary };
        
        if (!file.is_open())
        {

            MSEdebug::getInstance().debugError("Failed to open: " + filepath);

        }

        size_t fileSize = static_cast<size_t>(file.tellg());
        std::vector<char> buffer(fileSize);

        file.seekg(0);
        file.read(buffer.data(), fileSize);
        file.close();
        
        MSEdebug::getInstance().debugPassthrough(buffer.data());
        MSEdebug::getInstance().debugPassthrough("---------------------------------------------------------");

        std::string output = buffer.data();

        return output;

    }

And here´s the output I get when I look at my debug Output: (yes I´m trying to read a vertex shader)

#version 330 core

layout (location = 0) in vec3 aPos;

void main()
{
    gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
}²²²²
---------------------------------------------------------

Already thank you in advance for answering.

Upvotes: 1

Views: 468

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133112

std::string output = buffer.data();

Because data is not null-terminated, your output string is formed incorrectly. Use the constructor which also takes the length, i.e.

std::string output(buffer.data(), buffer.size());

Alternatively, make sure buffer is null-terminated (by taking it one byte larger and setting the last byte to 0)

Upvotes: 1

rustyx
rustyx

Reputation: 85531

Consider what happens on this line

std::string output = buffer.data();

buffer.data() return a char *, which needs to match one of std::string constructors.

The best one is std::string(const char*) - taking a pointer to a null-terminated C string.

But std::vector<char> is not null-terminated, hence the string "runs away" past the end of the data, stopping at a random location that happens to contain 0.

You should construct the string in some other way, for example:

std::string output{begin(buffer), end(buffer)};

Or

std::string output{buffer.data(), buffer.size()};

Or perhaps read directly into a string:

std::ostringstream sstr;
sstr << file.rdbuf();
return sstr.str();

Upvotes: 1

Related Questions