Working with Files
Every program in this section runs in your browser. The playground gives each run an empty directory, in memory here and on disk in CI, and both runs are checked against the same expected output. So a program first writes the file it then reads.
readFileAllocfails when the file size reaches the limit, not only when it passes it. A limit of 18 rejects an 18-byte file.- A missing
flush()loses data without an error.closedoes not know about the writer's buffer. - There is no append flag. To append, open the file and move the writer to its length with
seekTo. - The order of a directory listing is up to the filesystem. Sort it before any output or test depends on it.
- Joining CSV fields with commas loses data without an error. A comma inside a field becomes an extra column.
9 chapters.
- Open, Read, CloseThree ways to read a file, and what each one does when the file is bigger than you planned for.
- Reading Line by LineA line loop over a file, the three line endings it meets, a line longer than the buffer, and a large file through a small buffer.
- Writing Text FilesTruncate or keep, create only if new, append, the flush that was forgotten, and replacing a file in one step.
- Binary FilesA small binary format with a header, written one field at a time, and a reader that checks every byte it did not write.
- Random AccessA file of fixed-size records. Read record N without reading the ones before it, change one in place, and grow and shrink the file.
- Reading CSVA CSV reader as a four-state machine, with a trace of every byte, the cases splitting on commas gets wrong, and errors with line numbers.
- Writing CSVQuote a field only when it needs it, double the quotes inside it, and prove the writer by reading its output back.
- DirectoriesCreate a tree of directories, list one level, walk every level, rename a directory and delete the whole tree.
- When Things Go WrongWhat stat tells us, six file operations that fail and the error each one names, messages a person can act on, and cleaning up a half-written file.