Unit 5 · Lesson 614 minAcademic review pending

Same C, one new question: how is it organized

CS105ES already taught fopen, fread, and fwrite. This lesson adds one layer on top: given those mechanics, how should the records inside a file actually be organized?

Choose explanation

After this lesson

You should be able to

  • Recall the difference between text and binary file modes.
  • Explain why binary mode is required for records with a data hierarchy.
  • Connect this lesson's file organization choices to the specific fopen mode and function each would use.
01

A quick recall, not a re-teach

CS105ES Unit V already covered the C mechanics in full: fopen with a mode string, checking for NULL, fscanf and fgets for text mode, fread and fwrite for binary mode, and fseek for jumping to a computed position. Nothing about those functions changes here — this lesson is about the design decision above them, not the syntax.

02

Why records need binary mode

The previous lesson's data hierarchy — fields grouped into a fixed-size record — is exactly why file organization work uses fwrite and fread rather than fprintf and fscanf. Writing a whole struct in one fwrite call preserves its fixed size on disk, which is what makes Lesson 5's direct organization possible at all: a record's byte position is index times record size only when every record occupies identical, predictable space, and only binary mode guarantees that.

Text mode, by contrast, writes a number as variable-width digit characters — 7 takes one byte, 700 takes three — which makes computing a record's exact position from its index impossible without scanning everything before it. That single fact is the entire reason Lesson 5's direct organization requires binary files specifically.

Try it yourself

For each file organization from Lesson 5 — sequential, direct, indexed-sequential — name which C file mode (text or binary) and which function pair (fscanf/fprintf or fread/fwrite) fits, and justify direct organization's choice specifically.

Need a hint?

Ask which organizations need to compute a byte offset directly from a record's index.

Check the worked solution

Sequential organization works with either mode, since it never computes a position — text mode is common for human-readable logs. Direct organization requires binary mode with fread/fwrite specifically, because CS105ES Unit V's fseek(fp, index * sizeof(Record), SEEK_SET) trick — computing a byte offset directly from an index — only works when every record occupies an identical, predictable number of bytes. Indexed-sequential organization needs the same binary guarantee for its data portion, plus its separate index structure.

Quick check

Why does direct (random-access) file organization require binary mode rather than text mode?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

Text and Binary Files · Basic File Operations

Maps to course outcomes CO1, CO4.