Skip to content

Zig Readers & Writers

You’ve already used a writer to print to stdout and a reader to get lines from stdin. Those weren’t one-off tools: almost every stream in Zig 0.17, whether it’s a file, a socket, a pipe or a chunk of memory, speaks through the same two types, std.Io.Writer and std.Io.Reader. Learn them once and you can read and write anything. This page shows how they’re built, how to write code that works with any of them, and the two mistakes that bite most people.

Here’s the stdout writer from Zig Output again:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
var buffer: [256]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer);
const out = &stdout_writer.interface;
try out.print("{d} apples\n", .{3});
try out.flush();
}

Output:

3 apples

There are two things here, and it helps to name them:

  • stdout_writer is a std.Io.File.Writer: the concrete thing that knows how to send bytes to one particular file.
  • stdout_writer.interface is a std.Io.Writer: the general part with print, writeAll, flush and friends. Every kind of writer has one.

The buffer you hand over lives in that interface. print copies bytes into the buffer, which is cheap, and only when the buffer fills up (or you call flush) does the interface ask the concrete writer to really send them. Readers work the same way in reverse: the reader fills its buffer from the source in big chunks, and functions like takeDelimiter hand you pieces of that buffer.

Write your functions against *std.Io.Writer and they work with every kind of writer. Here’s one function sending text to three very different places:

const std = @import("std");
fn writeReport(w: *std.Io.Writer, name: []const u8, score: u32) !void {
try w.print("{s}: {d} points\n", .{ name, score });
}
pub fn main(init: std.process.Init) !void {
// 1. stdout
var buf: [256]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &buf);
const stdout = &stdout_writer.interface;
try writeReport(stdout, "Ana", 42);
try stdout.flush();
// 2. a fixed buffer in memory
var mem: [64]u8 = undefined;
var fixed: std.Io.Writer = .fixed(&mem);
try writeReport(&fixed, "Ben", 7);
std.debug.print("in memory: {s}", .{fixed.buffered()});
// 3. memory that grows as needed
var growing: std.Io.Writer.Allocating = .init(init.gpa);
defer growing.deinit();
try writeReport(&growing.writer, "Cleo", 99);
try writeReport(&growing.writer, "Dev", 12);
std.debug.print("allocated:\n{s}", .{growing.written()});
}

Output:

Ana: 42 points
in memory: Ben: 7 points
allocated:
Cleo: 99 points
Dev: 12 points

The three writers you’ll meet most:

  • A file writer (file.writer(io, &buffer), then .interface) for stdout, stderr and files. Needs flush.
  • std.Io.Writer.fixed(&array) writes into an array you own. buffered() gives you what’s been written so far. No allocation, no flush needed.
  • std.Io.Writer.Allocating grows on the heap as you write. Pass &growing.writer to functions, read the text with written(), and free it with deinit().

writeReport has no idea which one it got, and it doesn’t need to. That also makes it easy to test: write into a fixed or Allocating writer and compare the text.

A fixed writer can’t grow. When the text doesn’t fit, writing fails with error.WriteFailed, and you keep whatever did fit:

const std = @import("std");
pub fn main() !void {
var mem: [8]u8 = undefined;
var w: std.Io.Writer = .fixed(&mem);
w.print("this is too long for eight bytes", .{}) catch |err| {
std.debug.print("error: {t}, kept: \"{s}\"\n", .{ err, w.buffered() });
};
}

Output:

error: WriteFailed, kept: "this is "

Notice how short the error is: every std.Io.Writer function fails with just error.WriteFailed, and every reader function with error.ReadFailed (plus EndOfStream where the data can run out). The interface keeps its error list small on purpose, so generic code doesn’t have to handle “disk full” and “connection reset” and fifty other things.

The real reason isn’t lost, though. File writers and readers store it in an err field:

const std = @import("std");
pub fn main() void {
var buf: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(std.Io.failing, &buf);
const out = &stdout_writer.interface;
out.print("hello\n", .{}) catch unreachable; // fits in the buffer
out.flush() catch |err| {
std.debug.print("flush: {t}\n", .{err});
std.debug.print("real reason: {?t}\n", .{stdout_writer.err});
};
}

Output:

flush: WriteFailed
real reason: BrokenPipe

We used std.Io.failing from Zig Io Interface to fake a stdout whose other end is closed, which is what happens for real when you run ./app | head -1 and head quits early. The print worked because it only filled the buffer; the flush is what actually hit the closed pipe.

On the reading side you already know takeDelimiter from Zig Reading Input. std.Io.Reader.fixed("...") makes a reader over a string, which is perfect for trying things out:

const std = @import("std");
pub fn main() !void {
var r: std.Io.Reader = .fixed("apples\nbananas\ncherries");
while (try r.takeDelimiter('\n')) |line| {
std.debug.print("[{s}]\n", .{line});
}
}

Output:

[apples]
[bananas]
[cherries]

takeDelimiter returns null at the end of the data, so the while stops by itself, and the last line counts even without a final newline. The reader has a few more moves, and the names tell you what they do:

  • take reads bytes and moves past them: take(n), takeByte(), takeDelimiter('\n').
  • peek looks at bytes without moving past them: peek(n), peekByte().
  • toss skips bytes you’ve already peeked at: toss(n).
const std = @import("std");
pub fn main() !void {
var r: std.Io.Reader = .fixed("GIF89a and the rest");
const magic = try r.take(6);
std.debug.print("magic: {s}\n", .{magic});
const next = try r.peekByte();
std.debug.print("next byte: '{c}' (still there)\n", .{next});
r.toss(1);
const word = (try r.takeDelimiter(' ')).?;
std.debug.print("word: {s}\n", .{word});
}

Output:

magic: GIF89a
next byte: ' ' (still there)
word: and

Peeking is handy when you need to look ahead before deciding what to do, like checking the first bytes of a file to see what format it is.

Writers and readers handle raw bytes too, not just text. writeInt and takeInt turn integers into bytes and back, and you choose the byte order (.little or .big), which matters for file formats and network protocols:

const std = @import("std");
pub fn main() !void {
var mem: [16]u8 = undefined;
var w: std.Io.Writer = .fixed(&mem);
try w.writeInt(u16, 513, .little);
try w.writeInt(u32, 0xCAFEBABE, .big);
std.debug.print("bytes: {any}\n", .{w.buffered()});
var r: std.Io.Reader = .fixed(w.buffered());
const a = try r.takeInt(u16, .little);
const b = try r.takeInt(u32, .big);
std.debug.print("{d} {x}\n", .{ a, b });
_ = r.takeByte() catch |err| std.debug.print("then: {t}\n", .{err});
}

Output:

bytes: { 1, 2, 202, 254, 186, 190 }
513 cafebabe
then: EndOfStream

513 is 0x0201, so little-endian stores 1 then 2. 0xCAFEBABE in big-endian keeps its bytes in the order you read them. When the data runs out, take functions return error.EndOfStream.

print can call a method on your own struct. Give the struct a pub fn format that takes a *std.Io.Writer, and use {f} in the format string:

const std = @import("std");
const Point = struct {
x: i32,
y: i32,
pub fn format(p: Point, w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.print("({d}, {d})", .{ p.x, p.y });
}
};
pub fn main() !void {
const p: Point = .{ .x = 7, .y = 8 };
std.debug.print("point: {f}\n", .{p});
var scratch: [64]u8 = undefined;
var counter: std.Io.Writer.Discarding = .init(&scratch);
try counter.writer.print("{f} and {f}", .{ p, Point{ .x = -3, .y = 40 } });
std.debug.print("that text is {d} bytes\n", .{counter.fullCount()});
}

Output:

point: (7, 8)
that text is 19 bytes

Because format writes to a *std.Io.Writer, the same method works for std.debug.print, stdout, files and memory. The second half shows one more writer: std.Io.Writer.Discarding throws the bytes away and only counts them, a cheap way to measure how long some output would be. Zig Format Strings has more on {f}.

This one is nasty because it compiles fine. Look at the line marked bug:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
var buffer: [64]u8 = undefined;
const stdout_writer = std.Io.File.stdout().writer(init.io, &buffer);
var out = stdout_writer.interface; // bug: a copy, not a pointer
try out.print("hello\n", .{});
try out.flush();
}

When we ran it, it printed nothing and crashed:

Segmentation fault at address 0x79

out is a copy of the interface, sitting somewhere else in memory. When the copy needs to flush, it works out where the File.Writer around it lives from its own address, and there’s nothing there. The fix is the & you’ve seen in every example:

var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer);
const out = &stdout_writer.interface;

You’ll find readers and writers all over the standard library:

You have Get a writer Get a reader
stdout / stderr / stdin File.stdout().writer(io, &buf) File.stdin().reader(io, &buf)
an open file file.writer(io, &buf) file.reader(io, &buf)
memory you own std.Io.Writer.fixed(&array) std.Io.Reader.fixed(bytes)
memory that grows std.Io.Writer.Allocating.init(gpa)

Then you use .interface (or .writer on Allocating) to get the *std.Io.Writer or *std.Io.Reader. Zig File I/O shows the file versions in detail.

Write fn table(w: *std.Io.Writer, n: u32) !void that writes the lines 1 x 3 = 3 up to n x 3. Call it with an Allocating writer for n = 3 and print the result with std.debug.print.

Hint: var aw: std.Io.Writer.Allocating = .init(init.gpa); defer aw.deinit();, then table(&aw.writer, 3) and aw.written().

Show solution
const std = @import("std");
fn table(w: *std.Io.Writer, n: u32) !void {
var i: u32 = 1;
while (i <= n) : (i += 1) {
try w.print("{d} x 3 = {d}\n", .{ i, i * 3 });
}
}
pub fn main(init: std.process.Init) !void {
var aw: std.Io.Writer.Allocating = .init(init.gpa);
defer aw.deinit();
try table(&aw.writer, 3);
std.debug.print("{s}", .{aw.written()});
}

Output:

1 x 3 = 3
2 x 3 = 6
3 x 3 = 9

table only knows it has a *std.Io.Writer. In main you could pass a stdout writer instead and it would work the same.

Read the line "name,age,city" with std.Io.Reader.fixed and print each comma-separated field on its own line, numbered.

Hint: takeDelimiter(',') works with any byte, not only '\n'.

Show solution
const std = @import("std");
pub fn main() !void {
var r: std.Io.Reader = .fixed("name,age,city");
var n: usize = 1;
while (try r.takeDelimiter(',')) |field| : (n += 1) {
std.debug.print("{d}: {s}\n", .{ n, field });
}
}

Output:

1: name
2: age
3: city

The last field has no comma after it, but takeDelimiter still returns it before giving null.

Give this struct a format method so that std.debug.print("{f}\n", .{t}) prints 21.5 C.

const Temp = struct {
celsius: f32,
};

Hint: pub fn format(t: Temp, w: *std.Io.Writer) std.Io.Writer.Error!void, and use {d} for the float.

Show solution
const std = @import("std");
const Temp = struct {
celsius: f32,
pub fn format(t: Temp, w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.print("{d} C", .{t.celsius});
}
};
pub fn main() void {
const t: Temp = .{ .celsius = 21.5 };
std.debug.print("{f}\n", .{t});
}

Output:

21.5 C

The method must be pub, and {f} is what tells print to call it.

  • A stream has two layers: the concrete writer or reader (like File.Writer) and its general .interface (std.Io.Writer / std.Io.Reader).
  • The buffer lives in the interface, so most writes are just memory copies until the buffer fills or you flush.
  • Write functions against *std.Io.Writer or *std.Io.Reader so they work with files, stdio, memory and tests.
  • Writer.fixed, Writer.Allocating and Reader.fixed give you streams over memory.
  • Interface errors are just WriteFailed and ReadFailed; file streams keep the real reason in .err.
  • Readers take, peek and toss; what they return is borrowed from the buffer.
  • Always use a pointer to .interface, never a copy.

Next up: Zig Async & Futures, running several tasks at the same time with io.async and await.

Quick check

1. What type should a function take so it can write to stdout, a file or memory?
2. A fixed writer over an 8-byte array is asked to print 20 bytes. What happens?
3. What is the difference between peekByte() and takeByte()?
4. Why is var out = stdout_writer.interface; a bug?