I've been trying to load my vertex shader from a file in c. Here is my code for loading the characters in a file into a string:
char* path = "shaders/vertex_shader.glsl";
if (!fopen(path, "r")) {
printf("Could not open shader file! %s", path);
exit(1);
}
FILE* shader = fopen(path, "r");
fseek(shader, 0, SEEK_END);
long file_size = ftell(shader);
rewind(shader);
char *vertex_shader_code = malloc(sizeof(char) * file_size 1);
fread(vertex_shader_code, sizeof(char), file_size, shader);
vertex_shader_code[file_size] = '\0';
printf("%s", vertex_shader_code);
fclose(shader);
The vertex_shader.glsl
file looks like this:
#version 330 core
layout (location = 0) in vec3 positions;
void main() {
gl_Position = vec4(positions.x, positions.y, positions.z, 1.0);
}
However, whenever I print out the vertex_shader_code
string I get a bunch of garbage characters at the bottom of the file:
#version 330 core
layout (location = 0) in vec3 positions;
void main() {
gl_Position = vec4(positions.x, positions.y, positions.z, 1.0);
}
════════
Also whenever, I try to compile the shader I get the following error:
0(8) : error C0000: syntax error, unexpected $undefined at token "<undefined>"
Code for compiling the vertex shader:
void checkShaderCompilation(int shader_type_number, GLuint shader) {
int success;
char log[512];
char* shader_type;
switch (shader_type_number) {
case 0:
shader_type = "Vertex Shader";
break;
case 1:
shader_type = "Fragment Shader";
break;
default:
printf("Invalid number has been provided for the shader_type_number (check function declaration)\n");
return;
}
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(shader, 512, NULL, log);
printf(" %s \n Compilation ERROR:\n %s\n", shader_type, log);
exit(1);
}
else {
printf("%s compiled successfully!\n", shader_type);
}
}
/* Compiling the vertex shader */
vertex_shader_object = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader_object, 1, &vertex_shader_code, NULL);
glCompileShader(vertex_shader_object);
checkShaderCompilation(0, vertex_shader_object);
CodePudding user response:
You have various off-by-one errors in your code. That part that calculates file_size
and reads the shader should be (untested)...
long file_size = ftell(shader);
rewind(shader);
char *vertex_shader_code = malloc(sizeof(char) * file_size 1);
fread(vertex_shader_code, sizeof(char), file_size, shader);
vertex_shader_code[file_size] = '\0';
Notes:
- I've removed the cast of the value returned by
malloc
. See here. sizeof(char)
is essentially redundant as it always evaluates to 1.
CodePudding user response:
It appears that I just had to open the file in binary mode:
FILE* shader = fopen(path, "rb");