cfread

Trying to understand fread


I have a datafile.

#version 460 core
out vec4 FragColor;

void main()
{
    FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}

And I am trying to read the contents of it with fread.

    FILE *fshader;
    char *fbuffer;
    long fsize;

    fshader = fopen("src/graphics/_fragment.shader", "r");

    fseek(fshader, 0L, SEEK_END); 
    fsize = ftell(fshader); 
    rewind(fshader);

    fbuffer = (char *)malloc(fsize + 1);
    fread(fbuffer, 1, fsize, fshader); 
    fbuffer[fsize] = '\0';

But I don't understand how fread works. It keeps reading 6 characters more than it should.

#version 460 core
out vec4 FragColor;

void main()
{
    FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}_to_te

Solution

  • There are 2 possible solutions:

    1. Either specify that the file has a binary format (to save \r characters):
    fshader = fopen("src/graphics/_fragment.shader", "rb");
    
    1. Either put the 0-terminator in the position obtained after reading (to ignore \r characters):
    size_t _fsize;
    _fsize = fread(fbuffer, 1, fsize, fshader);
    fbuffer[_fsize] = '\0';