Search code examples
cc-stringscfile

how to load a c string from a file


my code keeps throwing a segmentation fault from internal c libraries, my code is the following:

        char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
        FILE *shaderFile;

        shaderFile = fopen("./shaders/vertex.glsl", "r");

        if(shaderFile)
        {
            //TODO: load file
            for (char *line; !feof(shaderFile);)
            {
                fgets(line, 1024, shaderFile);
                strcat(vertexShaderCode, line);
            }

it is meant to load all the data from a file as a c string, line by line. can anyone help?


Solution

  • You want this:

    char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
    FILE *shaderFile;
    
    shaderFile = fopen("./shaders/vertex.glsl", "r");
    if (shaderFile == NULL)
    {
       printf("Could not open file, bye.");
       exit(1);
    }
    
    char line[1024];
    while (fgets(line, sizeof(line), shaderFile) != NULL)
    {
       strcat(vertexShaderCode, line);
    }
    

    You still need to make your that there is no buffer overflow. Possibly you need touse realloc in order to expand the buffer if the initial length of the buffer is too small. I leave this as an exercise to you.


    Your wrong code:

        char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
        FILE *shaderFile;
    
        shaderFile = fopen("./shaders/vertex.glsl", "r");  // no check if fopen fails
    
        for (char *line; !feof(shaderFile);)   // wrong usage of feof
        {                                      // line is not initialized
                                               // that's the main problem
            fgets(line, 1024, shaderFile);
            strcat(vertexShaderCode, line);    // no check if buffer overflows
        }