chapter three

3 I/O with utility

 

This chapter covers

  • Interacting with files in a cross-platform manner
  • Thinking critically about memory management with Allocators
  • Making code reliable with errors and error sets
  • Loops, defer, and error-based control flow mechanisms
  • Using the Zig build system and comptime to customize compiled programs

We’re about to write cat. Multiple times. You know cat, right? It’s a standard and ubiquitous program for shell scripting, made for concatenating files and commonly used to print file contents to the console.

I can hear you groan through the pages. Cat is so elementary and straightforward, isn’t it? How could such a program even contain enough content to deserve a chapter in this otherwise excellent Zig book?

Well, I aim to provide a grounded view on Zig and perhaps systems programming in general. The programs that underpin the world’s infrastructure, the programs you use every day without even a moment of consideration, the programs you couldn’t live without — these programs don’t need to be complex. They don’t need state-of-the-art algorithms or millions of lines of code. Useful code doesn’t need to be glamorous, it just needs to do the job you need in the way you expect.

3.1 Standard Zig

3.1.1 First and Foremost

3.1.2 Allocating with Allocators

3.1.3 Not just I/O

3.2 Meow, says cat

3.2.1 Adopting our first cat

3.2.2 Errors, catch and try

3.2.3 The interface pattern

3.3 Giving our cat more toys

3.3.1 For loops

3.3.2 Cat but it can concatenate

3.3.3 While loops

3.4 Questioning our cat

3.4.1 All of the cat errors

3.4.2 Defer to better resource management

3.4.3 Improvement can be a waste of time

3.4.4 Making the wheel nuclear grade

3.4.5 Writer, meet reader

3.5 Buffering and building with Buff and Bill

3.5.1 Why do we need build scripting?

3.5.2 Our build script

3.5.3 To buffer, or not to buffer