Skip to content

Instantly share code, notes, and snippets.

@z3t0
Last active July 1, 2017 09:37
Show Gist options
  • Save z3t0/1f4f5faf3cb0b82de8d11dbe592a305b to your computer and use it in GitHub Desktop.
Save z3t0/1f4f5faf3cb0b82de8d11dbe592a305b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// reads text from path to source
void read_file (char path[], char **source) {
FILE *f = fopen(path, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
*source = malloc(fsize + 1);
fread(*source, fsize, 1, f);
fclose(f);
// *source[fsize]='\0'; // this line causes a segfault
}
int main(){
char path[] = "read_file.c";
char *source;
read_file(path, &source);
printf("Source file:\n%s\n", source);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment