A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
Text mode is for humans. Binary mode is for programs. When you write a struct to a file in binary mode, you dump the raw bytes of memory directly to disk. No formatting. No translation. No newline conversion. What you write is exactly what you read back, byte for byte. This is how save files, cache files, network packet captures, and embedded firmware images work.
#include <stdio.h>#include <string.h>typedef struct {char name[32];int score;float grade;} Student;int main(void) {Student s;strncpy(s.name, "Alex", sizeof(s.name) - 1);s.name[sizeof(s.name) - 1] = '\0';s.score = 95;s.grade = 3.8f;FILE *fp = fopen("student.dat", "wb");if (fp == NULL) {perror("fopen");return 1;}size_t written = fwrite(&s, sizeof(Student), 1, fp);fclose(fp);printf("Wrote %zu record(s), %zu bytes\n", written, sizeof(Student));return 0;}
#include <stdio.h>typedef struct {char name[32];int score;float grade;} Student;int main(void) {Student s;FILE *fp = fopen("student.dat", "rb");if (fp == NULL) {perror("fopen");return 1;}size_t read_count = fread(&s, sizeof(Student), 1, fp);fclose(fp);if (read_count != 1) {printf("Failed to read record\n");return 1;}printf("Name: %s\n", s.name);printf("Score: %d\n", s.score);printf("Grade: %.1f\n", s.grade);return 0;}
That 40-byte struct is not portable across architectures. The int might be 4 bytes on one platform and 8 on another. The float representation might differ. Structure padding inserts unnamed bytes between fields, and the padding amount depends on the compiler and target. A binary file written on x86-64 Linux might be unreadable on ARM macOS. For truly portable binary formats, you serialize field by field in a defined byte order, not with a raw struct dump.
Never use raw struct fwrite/fread for data that must be read by a different architecture, compiler, or OS version. Define a wire format with explicit sizes (uint32_t, etc.) and byte order (network byte order via htons/htonl). Raw struct dumps are fine for same-machine caching. They are not fine for file formats distributed across systems.
Binary I/O is the bridge between your program's memory layout and persistent storage. Used carefully, it is fast and simple. Used carelessly, it creates files that break on the next platform or compiler update. Next: clearerr, which resets error flags on a stream after a recoverable failure.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.