从文件中读取GLSL着色器

Ole*_*iak 0 c++ opengl visual-studio-2012

我正在尝试从看起来像这样的文件中读取顶点和片段着色器

#version 330 core
in vec3 ourColor;

out vec4 color;

void main()
{
    color = vec4(ourColor, 1.0f);
}
Run Code Online (Sandbox Code Playgroud)

但是当我正在编译着色器时,我得到的错误就像'语法错误'. 在此输入图像描述

从文件中读取着色器代码的代码

const GLchar* readFromFile(const GLchar* pathToFile)
{
    std::string content;
    std::ifstream fileStream(pathToFile, std::ios::in);

    if(!fileStream.is_open()) {
        std::cerr << "Could not read file " << pathToFile << ". File does not exist." << std::endl;
        return "";
    }

    std::string line = "";
    while(!fileStream.eof()) {
        std::getline(fileStream, line);
        content.append(line + "\n");
    }

    fileStream.close();
    std::cout << "'" << content << "'" << std::endl;
    return content.c_str();
}
Run Code Online (Sandbox Code Playgroud)

BDL*_*BDL 5

这里的问题是,字符串content超出了函数末尾的范围,删除了整个内容.然后返回的是指向已释放的内存地址的指针.

const GLchar* readFromFile(const GLchar* pathToFile)
{
    std::string content; //function local variable
    ....
    return content.c_str();
} //content's memory is freed here
Run Code Online (Sandbox Code Playgroud)

我在这里看到两种方法来防止这种情况:要么返回字符串本身而不是指向其内存的指针,要么在堆上创建GLchar*数组并在那里复制内容.