typestar

Reading a whole file in C

Seek to the end for the size, allocate that plus one, read it back in one call.

#include <stdio.h>
#include <stdlib.h>

char *slurp(const char *path, long *length) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return NULL;
    }
    fseek(f, 0, SEEK_END);
    long size = ftell(f);
    rewind(f);

    char *buffer = (size < 0) ? NULL : malloc((size_t) size + 1);
    if (buffer == NULL) {
        fclose(f);
        return NULL;
    }
    size_t read = fread(buffer, 1, (size_t) size, f);
    buffer[read] = '\0';
    fclose(f);
    *length = (long) read;
    return buffer;
}

How it works

  1. ftell after seeking to the end gives the length.
  2. The extra byte is for the terminator you add yourself.
  3. The caller owns the buffer that comes back.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
435
Tokens
149
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 94 seconds.

Type this snippet

Step 4 of 4 in Opening & reading, step 4 of 12 in Files & I/O.

← Previous Next →