简体   繁体   中英

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.

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, ie

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)

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM