C fwrite and fread
Write a small binary payload and read one byte as an unsigned value.
A simple example
fwrite and fread
- Start with Two bytes, 0 and 7
- Do this Write and read the bytes
- Result 0, 7
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
./lessonRecover 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.
#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;
}
255
The final byte has all eight bits set and represents 255.
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. Text encoding can change byte values. Use binary I/O for this format.