读取GLSL文件时获取垃圾字符

Mic*_* IV 2 c++ opengl

我遇到了以下问题.我从文件中加载着色器.着色器程序在尝试编译时会抛出顶点和片段着色器的这些错误:

顶点信息

0(12):错误C0000:语法错误,在令牌""处意外$ undefined

片段信息

0(10):错误C0000:语法错误,在令牌""处意外$ undefined

在检查文件的加载内容时,我可以看到在着色器文件的开头和末尾附加了各种垃圾文本.就像这样:

#version 330

layout (location = 0) in vec4 position;
layout (location = 1) in vec4 color;

smooth out vec4 theColor;

void main()
{
gl_Position = position;
theColor = color;
}ýýýý««««««««þîþîþîþ
Run Code Online (Sandbox Code Playgroud)

加载着色器的方法如下所示:

void ShaderLoader::loadShaders(char * vertexShaderFile,char *fragmentShaderFile){


vs = loadFile(vertexShaderFile,vlen);
    fs = loadFile(fragmentShaderFile,flen);

}
char *ShaderLoader::loadFile(char *fname,GLint &fSize){
ifstream::pos_type size;
char * memblock;
string text;

// file read based on example in cplusplus.com tutorial
ifstream file (fname, ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
fSize = (GLuint) size;
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "file " << fname << " loaded" << endl;
text.assign(memblock);
}
else
{
cout << "Unable to open file " << fname << endl;
exit(1);
}
return memblock;
}
Run Code Online (Sandbox Code Playgroud)

我试图从UTF-8顶级ANSI更改编码,也试图在visual studio外编辑,但问题仍然存在.对此的任何帮助将不胜感激.

dat*_*olf 8

你正在使用C++,所以我建议你利用它.我建议您阅读std :: string,而不是读入自己分配的char数组:

#include <string>
#include <fstream>

std::string loadFileToString(char const * const fname)
{
    std::ifstream ifile(fname);
    std::string filetext;

    while( ifile.good() ) {
        std::string line;
        std::getline(ifile, line);
        filetext.append(line + "\n");
    }

    return filetext;
}
Run Code Online (Sandbox Code Playgroud)

这会自动处理所有内存分配和正确的分隔 - 关键字是RAII:资源分配是初始化.稍后您可以使用类似的内容上传着色器源

void glcppShaderSource(GLuint shader, std::string const &shader_string)
{
    GLchar const *shader_source = shader_string.c_str();
    GLint const shader_length = shader_string.size();

    glShaderSource(shader, 1, &shader_source, &shader_length);
}

void load_shader(GLuint shaderobject, char * const shadersourcefilename)
{
    glcppShaderSource(shaderobject, loadFileToString(shadersourcefilename));
}
Run Code Online (Sandbox Code Playgroud)