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:
- Open — read the file from disk into the buffer, set
dirty = false. - Save — write the buffer back to disk, set
dirty = false. Atomic save: write to<file>.tmpthenrename(2)over the original. The rename is atomic on POSIX; you can never end up with a half-written file. - Save As — prompt for a name (status-bar prompt loop), then save.
- 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 betweenopenandrenameis recoverable. - fsync(): After write, before rename, call
fsyncon the data file andfsyncon the directory. Otherwise the rename can land but the data hasn't hit disk yet. - Crash recovery: Vim's
.swpfile 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…