Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand fread

Tags:

c

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
like image 907
user2980746 Avatar asked Sep 16 '25 23:09

user2980746


1 Answers

My guess is that you are on Microsoft Windows and that the text file has \r\n line endings.

On Microsoft Windows, when reading the character combination \r\n in text mode, it will get translated to \n. However, when at the end of the file, ftell will give you the length of the file in untranslated bytes, even when in text mode. This means that as far as fread is concerned, your file has a length that is a few bytes shorter than reported by ftell.

For this reason, you should set the position of the terminating null character according to the number of bytes read by fread, by inspecting the return value of fread. You should not set it according to what ftell reported.

like image 85
Andreas Wenzel Avatar answered Sep 19 '25 14:09

Andreas Wenzel