file-handling · intermediate · ~15 min

Read a whole file as text

`fseek`/`ftell` to size a file, then a single `fread`.

Challenge

Read an entire file into a single heap buffer and NUL-terminate it so it is a valid C string.

Task

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.

Input

  • path: the file to read.
  • out_len: pointer that receives the number of bytes read (excluding the added NUL).

Output

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).

Example

file contains "abc"   ->   buffer = "abc", *out_len = 3
read_all("does-not-exist", &n)   ->   NULL

Edge cases

  • A missing/unopenable file returns NULL.
  • An empty file yields a 1-byte buffer (just the NUL) with *out_len = 0.

Rules

  • Allocate size + 1 bytes and NUL-terminate; the caller frees the result.

Input format

A file path and an out_len pointer that receives the byte count.

Output format

A malloc'd NUL-terminated buffer of the contents (caller frees), or NULL on failure.

Constraints

Allocate size + 1 and NUL-terminate; pair fopen with fclose.

Starter code

#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.