-1

So basically the way i'm allocating the buffer is by just doing it manually like this

vertexSource = "#version 150\n"
    "in  vec3 in_Position;\n"
    "void main()\n"
    "{\n"
    "gl_Position = vec4(in_Position.x, in_Position.y, in_Position.z, 1.0);\n"
    "}";
    
    fragmentSource = "#version 150\n"
    "precision highp float;\n"
    "out vec4 fragColor;"
    "void main()\n"
    "{\n"
    "fragColor = vec4(1.0,1.0,1.0,1.0);\n"
    "}";

As you can see that's not very convenient for me. I would rather have it where I can read from a file then have the computer do that work for me. So how would I go about doing that?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

-1

From the question it sounds like you want to read a file into memory, presumably from a known path? That is pretty straightforward:

#include <stdio.h>
#include <unistd.h>

char *readFile(char *filename) {
    FILE *fp = fopen(filename, "rb");
    size_t reserved = 1024; // how much space is reserved for the read buffer
    size_t stored = 0; // how much has been read so far
    char *buffer = malloc(reserved);

    for (;;) {
        size_t consumed;
        if (reserved == stored) {
            // buffer is empty, make it bigger
            reserved += 1024; // or similar 
            buffer = realloc(buffer, reserved);
        }
        consumed = fread(buffer + stored, reserved - stored, 1, fp);
        if (!consumed) {
            break;
        }
        stored += consumed;
    }

    // null-terminate the buffer
    buffer = realloc(buffer, stored + 1);
    buffer[stored] = '\0';

    fclose(fp);

    return buffer;
}

Remember to free() the returned buffer when you're done with it.

fluffy
  • 5,212
  • 2
  • 37
  • 67
  • 2
    [**Why is “while ( !feof (file) )” always wrong?**](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Andrew Henle Mar 29 '21 at 00:42
  • This is probably a opengl issue but I'm using this data type in opengl called a GLchar and when I try doing that I get this error "Array type 'GLchar *[255]' is not assignable" – Coder Husk Mar 29 '21 at 00:45
  • @CoderHusk You can read the file into memory as `char` first, and then worry about glchar conversions later. Also there is no [255] anywhere here so it is not really clear what you are doing. If you have trouble with a specific piece of code then post a new question including that code (as part of a minimal reproducible example). – M.M Mar 29 '21 at 04:30
  • @CoderHusk The OpenGL shader upload thing takes an array of lines of text, not a single text blob. Give it `&buffer` instead of `buffer`. – fluffy Mar 30 '21 at 01:06
  • @AndrewHenle Thanks, I've updated my answer accordingly. This is the first I've heard of that being a problem. I'm mystified as to why this answer has only gotten downvotes instead of suggested edits, though. – fluffy Mar 30 '21 at 01:08