Lesson 2 of 5
Text vs Binary Files & fread/fwrite
In **text mode**, `\n` is translated to/from the platform line ending (\r\n on Windows). In **binary mode**, bytes are passed through unchanged. For structured data (structs), always use binary mode with `fread`/`fwrite` - text-mode translations corrupt raw bytes. `fread(buf, size, count, fp)` returns the number of items successfully read (may be less than count on EOF or error).
Binary File I/O - Reading & Writing Struct Records
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ── The record type to store ────────────────────────────── */
typedef struct {
int id;
char name[32];
float grade;
} Record;
/* ── Write records to binary file ────────────────────────── */
int write_records(const char *path, const Record *records, int count) {
FILE *fp = fopen(path, "wb"); /* "wb" = write binary */
if (!fp) { perror("fopen write"); return -1; }
/* Write count header first */
if (fwrite(&count, sizeof(int), 1, fp) != 1) {
perror("fwrite header"); fclose(fp); return -1;
}
/* Write all records in one call */
size_t written = fwrite(records, sizeof(Record), (size_t)count, fp);
if ((int)written != count) {
perror("fwrite records"); fclose(fp); return -1;
}
fclose(fp);
return 0;
}
/* ── Read records from binary file ──────────────────────── */
Record *read_records(const char *path, int *out_count) {
FILE *fp = fopen(path, "rb"); /* "rb" = read binary */
if (!fp) { perror("fopen read"); return NULL; }
int count = 0;
if (fread(&count, sizeof(int), 1, fp) != 1) {
perror("fread header"); fclose(fp); return NULL;
}
Record *records = malloc((size_t)count * sizeof(Record));
if (!records) { fclose(fp); return NULL; }
size_t read = fread(records, sizeof(Record), (size_t)count, fp);
if ((int)read != count) {
perror("fread records"); free(records); fclose(fp); return NULL;
}
fclose(fp);
*out_count = count;
return records;
}
int main(void) {
Record students[] = {
{1, "Alice", 88.5f},
{2, "Bob", 91.0f},
{3, "Carol", 79.3f},
};
int n = (int)(sizeof(students) / sizeof(students[0]));
if (write_records("students.bin", students, n) != 0) return 1;
printf("Wrote %d records
", n);
int loaded = 0;
Record *data = read_records("students.bin", &loaded);
if (!data) return 1;
printf("Read %d records:
", loaded);
for (int i = 0; i < loaded; i++) {
printf(" %d %-10s %.1f
", data[i].id, data[i].name, data[i].grade);
}
free(data);
return 0;
}Common Mistakes
- Using text mode for binary data - `fopen("data.bin", "w")` on Windows translates `\n` (0x0A) to `\r\n` (0x0D 0x0A). Reading back in binary mode produces different bytes. Always use `"rb"`/`"wb"` for struct data.
- Not checking `fwrite` return value - `fwrite` may write fewer items than requested (disk full, network error). Always verify `fwrite(...) == expected_count`.
- Reading struct data written on a different architecture - struct padding and integer endianness differ between platforms. Binary files are not portable across architectures without serialization.
Tip
Tip
Practice Text vs Binary Files freadfwrite in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Binary I/O reads and writes raw memory structs directly to disk without text conversion
Practice Task
Note
Practice Task - (1) Write a working example of Text vs Binary Files freadfwrite from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Text vs Binary Files freadfwrite is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.
Key Takeaways
- In **text mode**, `\n` is translated to/from the platform line ending (\r\n on Windows).
- Using text mode for binary data - `fopen("data.bin", "w")` on Windows translates `\n` (0x0A) to `\r\n` (0x0D 0x0A). Reading back in binary mode produces different bytes. Always use `"rb"`/`"wb"` for struct data.
- Not checking `fwrite` return value - `fwrite` may write fewer items than requested (disk full, network error). Always verify `fwrite(...) == expected_count`.
- Reading struct data written on a different architecture - struct padding and integer endianness differ between platforms. Binary files are not portable across architectures without serialization.
Finished this lesson?