Search code examples
cparsingfile-ioc-strings

How to split a string along a line in C?


I've been following the Cherno's opengl series in c++ recently and wanted to give it a try in c. One thing I have been having a problem with is reading in the contents of the shader files so I can compile them. While I can read in the whole file, in the videos, it is recommended to use one file for both the vertex and fragment shaders. I need a way to break the file into two separate strings, one for the vertex shader, and one for the fragment shader. To help with this, at the top of each shader I added "#shader vertex" and "#shader fragment" to know when I need to split, as was recommended in the video. However, I don't really know how to go about this in c as the video was in c++ using fstream rather than c's file api.

It would be best to be able to read the string or file line by line to check if the markers are found and then write the contents / copy from the buffer to either the vertex or fragment shader strings as needed.

So far I have this

static char* FileToString(const char* filePath)
{
    //Load .shader file into two separate strings (one for vertex and one for fragment)
    FILE* source = fopen(filePath, "r");
    if(source == NULL)
    {
        printf("Failed to open %s!\n", filePath);
    }

    char* buffer = 0;
    long length;
    fseek(source, 0, SEEK_END);

    length = ftell(source);

    fseek(source, 0, SEEK_SET);
    buffer = (char*)malloc(length);

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

    fclose(source);
    
    return buffer;
}

Thanks for any help!


Solution

  • assuming vertex is first, do this after you read the whole file:

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

    this is the easiest way, after that you get 2 pointers, each pointing to a string containing your data. Assuming the data can be read as text. If it's binary data that can contain 0's, your approach of adding text will not easily work