typestar

Seeking within a file in C

fseek moves the cursor, ftell reports it, rewind sends it home.

#include <stdio.h>

int read_tail(const char *path, char *out, size_t n) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return 0;
    }
    if (fseek(f, -(long) n, SEEK_END) != 0) {
        rewind(f);
    }
    size_t read = fread(out, 1, n, f);
    out[read] = '\0';
    long where = ftell(f);
    fclose(f);
    return where > 0;
}

How it works

  1. SEEK_SET, SEEK_CUR and SEEK_END are the origins.
  2. A negative offset from SEEK_END reads the tail.
  3. Text-mode seeking is only defined for values ftell returned.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
294
Tokens
111
Three-star pace
100 tpm

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

Type this snippet

Step 1 of 3 in Positioning & streams, step 9 of 12 in Files & I/O.

← Previous Next →