Public Group

This topic is 2988 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I've been trying to load a GLSL shader from file for a day now. I got the shader working by hard coding it into a char array but I can't seem to load it from the damn file. I've tried 3 different methods so far to load it but nope, no luck (Source included for the method I think is cleanest). Here's the code I have now and I would appreciate it if someone could tell me what I'm doing wrong. Thanks.
const char* Shader::loadShaderSource(const string& filename) {
std::ifstream file;
file.open(filename.c_str());

if (!file) {
return(0);
}

std::stringstream stream;

stream << file.rdbuf();

file.close();

return(stream.str().c_str());
}


When I print out the result of the above function, there is no visible problems with the data. The error I get when linking the shader is: line 1: error C0000: syntax error, expected \$undefined at token "<undefined>" line 1: errorC0501: type name expected at token "<undefined>"

##### Share on other sites
Objects die when they go out of scope, so does that stream when the function returns, copy the file string out before it dies.

bool Shader::loadShaderSource(const string& filename, string& out) {    std::ifstream file;    file.open(filename.c_str());    if (!file) {        return false;    }    std::stringstream stream;    stream << file.rdbuf();    file.close();    out = stream.str();return true;}

##### Share on other sites
Yeah as mentioned above, the problem is with the lifetime of your string.
The c_str function returns a raw-pointer to the string's internal buffer, but when the string is destructed, this buffer is deallocated.

##### Share on other sites
Ah, thanks a lot both of you. I can't believe I didn't notice that -- must have looked over the code atleast 10 times!

• 37
• 12
• 10
• 10
• 9
• ### Forum Statistics

• Total Topics
631360
• Total Posts
2999556
×