Skip to content

Instantly share code, notes, and snippets.

@4e1e0603
Last active September 20, 2015 10:33
Show Gist options
  • Save 4e1e0603/24a04a54a04a7f07a0ce to your computer and use it in GitHub Desktop.
Save 4e1e0603/24a04a54a04a7f07a0ce to your computer and use it in GitHub Desktop.
/**
Reads the content and returns it as a string.
@param filename
@returns string
*/
const char * read_text(const char * filename)
{
assert(NULL != filename);
FILE * fp;
if (NULL == (fp = fopen(filename, "rb"))) {
fprintf(stderr, "Can't open the input file!\n");
exit(1);
}
if(0 != fseek(fp, 0, SEEK_END)) {
fprintf(stderr, "Can't seek the input file!");
exit(1);
}
size_t fsize = ftell(fp);
if(0 != fseek(fp, 0, SEEK_SET)) {
fprintf(stderr, "Can't seek the input file!");
exit(1);
}
// or rewind(fp);
char * str = (char *) malloc(fsize *sizeof(char));
if (fsize > fread(str, 1, fsize, fp)) {
fprintf(stderr, "Can't read the whole file!");
exit(1);
}
fclose(fp);
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment