file-handling · intermediate · ~15 min
`fseek`/`ftell` to size a file, then a single `fread`.
Read an entire file into a single heap buffer and NUL-terminate it so it is a valid C string.
Implement char *read_all(const char *path, size_t *out_len) that reads all bytes of path into a freshly allocated buffer, appends a trailing \0, stores the byte count in *out_len, and returns the buffer. No main — the grader calls it.
path: the file to read.out_len: pointer that receives the number of bytes read (excluding the added NUL).A malloc-ed buffer holding the file contents plus a terminating \0. The caller frees it. Returns NULL on failure (e.g. the file cannot be opened).
file contains "abc" -> buffer = "abc", *out_len = 3
read_all("does-not-exist", &n) -> NULL
NULL.*out_len = 0.size + 1 bytes and NUL-terminate; the caller frees the result.A file path and an out_len pointer that receives the byte count.
A malloc'd NUL-terminated buffer of the contents (caller frees), or NULL on failure.
Allocate size + 1 and NUL-terminate; pair fopen with fclose.
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
char *read_all(const char *path, size_t *out_len) {
/* TODO */
return NULL;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.