Skip to content

Instantly share code, notes, and snippets.

Created June 22, 2022 03:30
What would you like to do?
// Read file as binary, but append \0 to the end of the buffer
// filename: name of file to read
// buf : if file read successfully, this will be set to a pointer to the file contents on the heap
// len : if file read successfully, this will be set to the file length
// Returns 0 on success, negative error code on failure (see stderr for more info)
// WARN: you must free(buf) when you're done with it!!
int ta_file_read_all(const char *filename, char **buf, size_t *len)
// Open file
FILE *fs = fopen(filename, "rb");
if (!fs) {
fprintf(stderr, "Unable to open %s for reading\n", filename);
return -1;
// Calculate length
fseek(fs, 0, SEEK_END);
long tell = ftell(fs);
if (tell < 0) {
fprintf(stderr, "Unable to determine length of %s\n", filename);
return -2;
// Error on empty file
assert(tell > 0);
size_t buflen = (size_t)tell + 1;
char *buffer = (char *)calloc(1, buflen); // extra byte for nil
if (!buffer) {
fprintf(stderr, "Failed to allocate buffer\n");
return -3;
size_t read = fread(buffer, 1, tell, fs);
if (read != buflen - 1) {
fprintf(stderr, "Failed to read entire file\n");
return -4;
// Close file
*buf = buffer;
*len = buflen;
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment