Skip to content

Instantly share code, notes, and snippets.

@harschware
Created April 7, 2011 16:27
Show Gist options
  • Select an option

  • Save harschware/908136 to your computer and use it in GitHub Desktop.

Select an option

Save harschware/908136 to your computer and use it in GitHub Desktop.
shows code to read a file into a correctly sized string buffer using malloc
// adapted from stackoverflow post: http://stackoverflow.com/questions/3233645/read-multiples-lines-from-file-to-a-string-in-c/3233744#3233744 by user http://stackoverflow.com/users/346905/faisal
char * readFile( const char * fileName ) {
// open the file
FILE* fp = fopen( fileName, "r");
if (fp == NULL) {
fprintf(stderr,"ERROR: couldn't open file\n");
exit(1);
}
// seek to the end to get the length
// you may want to do some error-checking here
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
// we need to seek back to the start so we can read from it
fseek(fp, 0, SEEK_SET);
// allocate a block of memory for this thing
// the +1 is for the nul-terminator
char* buffer = (char *)malloc((length + 1) * sizeof(char));
if (buffer == NULL) {
fprintf(stderr,"ERROR: not enough memory to read file\n");
exit(1);
}
// now for the meat. read in the file chunk by chunk till we're done
long offset = 0;
while (!feof(fp) && offset < length) {
offset += fread(buffer + offset, sizeof(char), length-offset, fp);
}
// buffer now contains your file
// but if we're going to print it, we should nul-terminate it
buffer[offset] = '\0';
// always close your file pointer
fclose(fp);
return buffer;
} // end function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment