Library contents

C fseek and fgetc

Seek to a byte offset before reading a fixed-width record.

A simple example

fseek and fgetc

  1. Start with Three bytes, 4, 7, 9
  2. Do this Read at byte offset 1
  3. Result 7
Offsets start at zero. Moving one byte past the start selects the second byte.

Syntax

C syntax
fseek(board, 2, SEEK_SET)
Run these examples in C

Save one example at a time as lesson.c. Use C17 on macOS or Linux with a POSIX shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Read the third locker status

A parcel desk stores one byte for each locker. Because the records have fixed width, the operator can read the third locker directly without first processing the other two statuses.

From the programunsigned char statuses[] = {6, 8, 9}
Result9
lesson.c
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    FILE *board = tmpfile();
    if (!board) return 1;
    unsigned char statuses[] = {6, 8, 9};
    int ok = fwrite(statuses, 1, sizeof statuses, board) == sizeof statuses;
    int value = EOF;
    if (ok && fseek(board, 2, SEEK_SET) == 0) value = fgetc(board);
    fclose(board);
    if (value == EOF) return 1;
    printf("%d\n", value);
    return 0;
}
Output
9

The third locker occupies offset two and stores the value nine.

Advertisements

Read a display preset

A museum sign saves three brightness levels as individual bytes. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?

Given12 · 80 · 200 | offset 2
Worked result200

Read the first locker state

A desk stores two status values in a compact file. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?

Given7 · 25 | offset 0
Worked result7

What to watch for

These C examples use POSIX file APIs on macOS or Linux. Offsets refer to bytes. Variable-length text needs a different indexing strategy.

Documentation for fseek and fgetc