C fseek and fgetc
Seek to a byte offset before reading a fixed-width record.
A simple example
fseek and fgetc
- Start with Three bytes, 4, 7, 9
- Do this Read at byte offset 1
- Result 7
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
./lessonRead 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.
#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;
}
9
The third locker occupies offset two and stores the value nine.
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?
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?
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.