Library contents

C fwrite and fread

Write a small binary payload and read one byte as an unsigned value.

A simple example

fwrite and fread

  1. Start with Two bytes, 0 and 7
  2. Do this Write and read the bytes
  3. Result 0, 7
Binary I/O preserves the zero byte as part of the data.

Syntax

C syntax
fread(bytes, 1, sizeof bytes, stream)
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

Recover the brightest setting from a preset

A camera club stores three brightness levels in a compact binary preset. Read the saved bytes back and display the brightest setting as an unsigned number on the familiar 0–255 scale.

From the programunsigned char levels[] = {0, 64, 255}, received[3]
Result255
lesson.c
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    FILE *preset = tmpfile();
    if (!preset) return 1;
    unsigned char levels[] = {0, 64, 255}, received[3];
    int ok = fwrite(levels, 1, sizeof levels, preset) == sizeof levels;
    if (ok && fseek(preset, 0, SEEK_SET) == 0 &&
        fread(received, 1, sizeof received, preset) == sizeof received)
        printf("%u\n", (unsigned)received[2]);
    else ok = 0;
    fclose(preset);
    return ok ? 0 : 1;
}
Output
255

The final byte has all eight bits set and represents 255.

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. Text encoding can change byte values. Use binary I/O for this format.

Documentation for fwrite and fread