0

I'm trying to parse my opengl .shader files into a string in c using the file i/o functions. For some reason, when the file size gets big enough (past 447 bytes exactly for some reason) there are garbage characters at the end of the string, preventing the shader from being compiled.

I've been trying to fix this all day and can't seem to figure out why it doesn't work.

There is another question similar to this: similar question but I tried everything suggested and nothing worked

Here's the code:

static char* FileToString(const char* filePath)
{
    FILE* source = fopen(filePath, "r");
    if(source == NULL)
    {
        printf("Failed to open file!\n");
        return NULL;
    }

    char* buffer = 0;
    int length = 0;
    fseek(source, 0, SEEK_END);
    length = ftell(source);
    rewind(source);

    printf("Length: %d\n", length);
    buffer = (char*)malloc(length);

    if(buffer)
    {
        fread(buffer, 1, length, source);
    }

    fclose(source);

    return buffer;
}

shader ParseShader(const char* filePath)
{
    char* buffer = FileToString(filePath);

    //printf("%s\n", buffer);

    char *vertex = buffer + sizeof("#shader vertex") - 1;
    char *fragment = strstr(vertex, "#shader fragment");
    *fragment = '\0';
    fragment += sizeof("#shader fragment") - 1;

    //printf("VERTEX: \n %s", vertex);
    printf("FRAGMENT: \n %s", fragment);

    shader program = {vertex, fragment};

    return program;

}

And here is the shader file:

#shader vertex
#version 330 core
layout(location = 0) in vec4 position;
layout(location = 1) in vec3 colors;
layout(location = 2) in vec2 texCoords;
out vec4 f_Color;
out vec2 f_texCoords;
void main()
{
    gl_Position = position;
    f_Color = vec4(colors, 1.0);
    f_texCoords = texCoords;
}

#shader fragment
#version 330 core
in vec2 f_texCoords;
in vec4 f_Color;
out vec4 color;
uniform sampler2D containerTexture;
void main()
{
    color = f_Color;
}

I've tried making the last character '\0', setting the mode to rb, cutting off parts of the string, etc. but none of it worked

genpfault
  • 51,148
  • 11
  • 85
  • 139
Dr-Galunga
  • 15
  • 4
  • `buffer = (char*)malloc(length);` You need to allocate `length + 1` and 0 terminate the string. `buffer[length] = 0;` You could also use `calloc` instead which would set the buffer to all zeroes. The answer in the question you linked has exactly what you need in it. – Retired Ninja Jan 07 '23 at 02:27
  • Hint: What is a string? – user253751 Jan 07 '23 at 02:35
  • 2
    Any attempt to create a [c] question with "garbage characters at the end of a string" should just automatically be redirected to https://stackoverflow.com/questions/270708/string-array-with-garbage-character-at-end – Tibrogargan Jan 07 '23 at 02:38

0 Answers0