Skip to content

Instantly share code, notes, and snippets.

@a3f
Last active September 25, 2018 15:14
Show Gist options
  • Save a3f/8559fadf4751e245298fa7a20e0f7b86 to your computer and use it in GitHub Desktop.
Save a3f/8559fadf4751e245298fa7a20e0f7b86 to your computer and use it in GitHub Desktop.
Slurp file into buffer with C stdio
long fslurp(char **buf, long *len, FILE *fp)
{
size_t new_len;
long size, start = ftell(fp);
if (start == -1 || fseek(fp, 0, SEEK_END) == -1)
return -1;
if ((size = ftell(fp)) == -1)
return -1;
size -= start;
if (fseek(fp, start, SEEK_SET) == -1)
return -1;
if (*buf) {
if (!len) return -1;
new_len = fread(*buf, 1, *len, fp);
if (ferror(fp)) return -1;
if (new_len < (size_t)*len)
(*buf)[new_len] = '\0';
} else {
*buf = malloc(size + 1);
new_len =fread(*buf, 1, size, fp);
if (ferror(fp)) {
free(*buf);
*buf = NULL;
return -1;
}
(*buf)[new_len] = '\0';
}
if (len) *len = new_len;
return size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment