⚡ Zig Guide LiveUnofficialbut fully verified
✓ Zig 0.18.0-dev.753+1420479beWhat's newOn an older Zig?Blograylib-zig

Unix Tools

This section rebuilds seven tools that you use every day, from zero. Each chapter is one complete program and teaches one technique. The first four techniques are streaming reads, a state machine, search, and ownership of the lines that you sort. The other three are a split on a delimiter, the conversion of a number to text, and the decision about what to rebuild. The tools are small enough that you can understand them completely. They are also old enough that their design is the lesson.

  1. cat is a loop around a fixed buffer. The buffer size is a decision about memory, not about correctness. Thus cat can copy a file that is larger than memory.
  2. wc counts the transitions into a word, not the words. The counter is a state machine, and thus spaces at the start and double spaces cost nothing.
  3. To sort lines, you must own the lines. When the sorted output must live longer than the read buffer, you must decide who allocates.
  4. printf builds its digits backwards. Division is the only way to get the last digit of a number, and division gives the digits in reverse order.
  5. make is a topological sort over a graph of file timestamps. All the other parts of make are syntax.

7 chapters.

  • catA loop around one fixed buffer. For this reason, cat can copy a file that is larger than memory.
  • wcTo count words, count each time that the input goes into a word.
  • grepSearch is a loop over start positions, and the exit code is the answer.
  • sortTo sort lines is easy. To own the lines is the part that has a cost.
  • cutHow to split a line at a delimiter, and the edge cases that decide if the split is correct.
  • printfHow to change a number into text, one digit at a time, from the last digit to the first.
  • makeA dependency graph, a topological order, and a comparison of timestamps.