Skip to content

Instantly share code, notes, and snippets.

@pperon
Created March 24, 2015 21:18
Show Gist options
  • Save pperon/ffc1f13581fe5756e59d to your computer and use it in GitHub Desktop.
Save pperon/ffc1f13581fe5756e59d to your computer and use it in GitHub Desktop.
I'm tired of in-lining shader code and forgot how to read the contents of a file in C.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main()
{
const char *FILENAME = "shader.glsl";
FILE *shader;
#ifdef _WIN32
errno_t error = fopen_s(&shader, FILENAME, "r");
if (error == 0) {
#else
if (vs = fopen(FILENAME, "r")) {
#endif
struct stat st;
long fileSize;
if (stat(FILENAME, &st) == 0)
{
fileSize = st.st_size;
}
long charLength = sizeof(char) * fileSize;
char *source = malloc(charLength);
size_t retCode = fread(source, sizeof *source, charLength, shader);
for (unsigned int i = 0; i < retCode; i++)
{
printf("%c", source[i]);
}
free(source);
fgetc(stdin);
}
else
{
printf("Error loading file: %s", error);
fgetc(stdin);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment