Skip to content
File I/O & Dirty Flag
step 1/5

Reading — step 1 of 5

Read

~2 min readProduction

File I/O & Dirty Flag

Every editor needs three file operations and one piece of state:

  1. Open — read the file from disk into the buffer, set dirty = false.
  2. Save — write the buffer back to disk, set dirty = false. Atomic save: write to <file>.tmp then rename(2) over the original. The rename is atomic on POSIX; you can never end up with a half-written file.
  3. Save As — prompt for a name (status-bar prompt loop), then save.
  4. Dirty flag — set to true on any edit; cleared by save. Quit when dirty triggers a confirmation: kilo's WARNING!!! File has unsaved changes. Press Ctrl-Q 3 more times to quit. pattern.

Kilo's quit protocol is interesting: instead of a modal dialog, it requires the user to press the quit key several times in a row, with a counter that resets on any other key. That keeps the editor non-modal — power users blow through it; cautious users get the safety.

Other production touches we will skip but are worth knowing:

  • Backup file: Vim writes file.txt~ before saving so a power loss between open and rename is recoverable.
  • fsync(): After write, before rename, call fsync on the data file and fsync on the directory. Otherwise the rename can land but the data hasn't hit disk yet.
  • Crash recovery: Vim's .swp file is a transaction log of edits since the last save. After a crash, vim offers to replay it.
  • File watching: If the file changes on disk while the editor has it open (git pull, another editor), warn the user and offer to reload.

This lesson simulates the open/edit/save/quit state machine. You'll feel the rhythm: every state mutation either sets dirty or clears it.

Reference: kilo editorOpen, editorSave; vim :swap file format.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…