Skip to content

Instantly share code, notes, and snippets.

@dbechrd
Created June 22, 2022 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbechrd/947c01b99aae910704c40e2ec8ced990 to your computer and use it in GitHub Desktop.
Save dbechrd/947c01b99aae910704c40e2ec8ced990 to your computer and use it in GitHub Desktop.
// 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)
{
assert(filename);
assert(buf);
assert(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;
}
rewind(fs);
// 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
fclose(fs);
*buf = buffer;
*len = buflen;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment