-
-
Save benjamn/b269f2b4b0f0498e1b8f to your computer and use it in GitHub Desktop.
reading a file from a relative path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static char* read_file(const char* relative_name) | |
{ | |
size_t base_offset = strlen(__FILE__) - strlen("offgrid.c"); | |
size_t abs_length = base_offset + strlen(relative_name); | |
char* abs_name = (char*) malloc(sizeof(char) * (abs_length + 1)); | |
strcpy(abs_name, __FILE__); | |
abs_name[base_offset] = '\0'; | |
strcat(abs_name, relative_name); | |
FILE* f = fopen(abs_name, "r"); | |
free(abs_name); | |
if (f == NULL) { | |
return NULL; | |
} | |
fseek(f, 0, SEEK_END); | |
long len = ftell(f); | |
rewind(f); | |
char* buf = (char*) malloc(sizeof(char) * len); | |
if (buf == NULL) { | |
fclose(f); | |
return NULL; | |
} | |
if (fread(buf, sizeof(char), len, f) != len) { | |
fclose(f); | |
free(buf); | |
return NULL; | |
} | |
fclose(f); | |
return buf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment