Working with Files
Every program in this section runs in your browser. The playground starts each run in an empty directory. In your browser the directory is in memory, and in CI the directory is on disk. The two runs must give the same expected output. Thus each program writes a file before it reads the file.
readFileAllocfails when the file size reaches the limit, not only when the size is more than the limit. A limit of 18 rejects an 18-byte file.- A missing
flush()loses data without an error.closedoes not know about the buffer of the writer. - There is no append flag. To append, open the file and move the writer to the length of the file with
seekTo. - The filesystem decides the order of a directory listing. Sort the listing before output or a test depends on the order.
- If you join CSV fields with commas, you lose 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 larger than you expect.
- Read Line by LineA line loop over a file, three types of line ending, a line longer than the buffer, and a large file through a small buffer.
- Write Text FilesTruncate or keep, create only if new, append, the flush that the program forgot, and how to replace a file in one step.
- Binary FilesA small binary format with a header, written one field at a time, and a reader that checks each byte that it did not write.
- Random AccessA file of records of fixed size. Read record N and not the records before it, change one record in place, and make the file larger and smaller.
- Read CSVA CSV reader as a state machine with four states, a trace of each byte, the errors of a comma split, and line numbers.
- Write CSVQuote a field only when it needs quotes, write each quote in it two times, and read the output again to prove the writer.
- DirectoriesCreate a tree of directories, list one level, walk all levels, rename a directory and delete the full tree.
- When Things Go WrongWhat stat tells you, six file operations that fail and the error from each, messages for a person, and how to delete a half-written file.