Skip to content

Zig Output

So far you’ve printed everything with std.debug.print. It’s great for learning, but it has a secret: it doesn’t write to the same place as a normal program’s output. This page explains the two output streams every program has, when to use std.debug.print, how to write “real” output to stdout in Zig 0.16, and the one mistake almost everyone makes with it (forgetting to flush).

Every program you start from a terminal gets two output streams:

  • stdout (standard output) is for the program’s actual result: the report, the data, the answer.
  • stderr (standard error) is for messages about the program: progress, warnings, errors, debug notes.

In a terminal, both show up on your screen, so they look the same. The difference shows when you redirect output. > sends only stdout to a file, and | sends only stdout to the next program. Whatever goes to stderr still appears on your screen.

That split is useful. myprogram > result.txt can save clean results to a file while warnings stay visible to you instead of mixing into the data.

std.debug.print writes to stderr. It needs no setup, never fails (if writing goes wrong, it quietly gives up), and every call is written out before it returns.

const std = @import("std");
pub fn main() void {
std.debug.print("Starting...\n", .{});
std.debug.print("The answer is {d}\n", .{42});
}

Output:

Starting...
The answer is 42

You can see it go to stderr if you build the program and redirect its output:

Terminal window
zig build-exe answer.zig
./answer > out.txt

You’ll see:

Starting...
The answer is 42

Both lines still appear on your screen, and out.txt is empty, because nothing went to stdout. That’s exactly why the name has “debug” in it: it’s meant for messages to you, the developer.

Since Zig 0.16, anything that talks to the outside world (files, the terminal, the network) goes through an Io value. You get one from main by giving it a parameter:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
try std.Io.File.stdout().writeStreamingAll(init.io, "Hello, stdout!\n");
}

Output:

Hello, stdout!

This is the same Hello World the 0.17.1 language reference starts with. Three new things are going on:

  • main(init: std.process.Init) asks Zig to hand main some useful things when the program starts. init.io is the Io value. (Zig Main & Init covers the rest.)
  • std.Io.File.stdout() is the stdout stream, and writeStreamingAll(io, text) writes all of text to it.
  • Writing can fail: the disk can be full, or the program you’re piping into can close early. So the function returns an error if that happens, try passes any error up, and !void on main means “returns nothing, but might return an error”. You’ll learn the details in Zig Errors. For now, put try in front of anything that writes to stdout.

writeStreamingAll takes plain text. For {d}, {s} and the other slots from std.debug.print, use a writer. Writers in Zig come with a buffer: a chunk of memory where text collects before it’s sent out in one go.

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

Output:

Hello, buffered stdout!
2 + 2 = 4

Line by line:

  1. var buffer: [1024]u8 = undefined; makes room for 1024 bytes of text. undefined means “I don’t care what’s in it yet”, since the writer will fill it.
  2. std.Io.File.stdout().writer(init.io, &buffer) creates a writer for stdout that uses that buffer.
  3. const out = &stdout_writer.interface; gets the general-purpose writer part. It’s of type *std.Io.Writer, and that’s what has print, writeAll and writeByte. The same print works for files, sockets and memory too.
  4. out.print(...) works just like std.debug.print, but it puts the text into the buffer.
  5. out.flush() sends everything in the buffer to stdout.

Other handy writer functions: out.writeAll("text") for plain text and out.writeByte('!') for a single character.

Every time a program actually sends data out, it asks the operating system to do it (a system call), and that’s slow compared to copying bytes in memory. A buffer turns lots of small writes into a few big ones.

To see the difference, we printed 100,000 short lines on the 4-core Linux machine this site is tested on (release build, output sent to /dev/null). Your numbers will differ, but the gap won’t:

How System calls Time
Writer with no buffer (&.{}) 300,000 about 46 ms
Writer with a 4 KB buffer 266 about 2 ms

Without a buffer, each print here turned into three separate writes (the text, the number and the newline). With one, the writes are grouped into a few hundred. For a handful of lines it doesn’t matter. For a program that prints a lot, it matters a lot.

Here’s the mistake. Take the program above and leave out try out.flush();:

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

It compiles, runs and prints nothing at all. The text went into the buffer, and nobody sent the buffer out before the program ended. Zig doesn’t flush for you when main returns.

It’s even more confusing when the output is bigger than the buffer. A writer sends its buffer out by itself when it fills up, so you get part of your output:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
var buffer: [16]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer);
const out = &stdout_writer.interface;
try out.print("This line is longer than sixteen bytes.\n", .{});
try out.print("Short.\n", .{});
}

Output:

This line is longer than sixteen bytes.

The first line didn’t fit in the 16-byte buffer, so it was sent. Short. was still waiting in the buffer when the program ended, and it’s lost.

Because stdout is buffered and std.debug.print isn’t, mixing them can print things in a surprising order:

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("1. first, to stdout\n", .{});
std.debug.print("2. second, to stderr\n", .{});
try out.print("3. third, to stdout\n", .{});
try out.flush();
}

Output:

2. second, to stderr
1. first, to stdout
3. third, to stdout

Line 1 sat in the buffer until flush, but line 2 went out straight away. Nothing is broken: these are two separate streams, and each one is in order. If you need the debug line to appear after line 1, call out.flush() before the std.debug.print.

You can also make a buffered writer for stderr, with std.Io.File.stderr() instead of stdout(). It works exactly the same way, flush included.

For messages with a level, Zig has std.log. It writes to stderr and adds a label in front:

const std = @import("std");
pub fn main() void {
std.log.info("starting up, version {d}", .{1});
std.log.warn("low on {s}", .{"coffee"});
std.log.err("something failed", .{});
std.log.debug("a detail only for debug builds", .{});
}

Output:

info: starting up, version 1
warning: low on coffee
error: something failed
debug: a detail only for debug builds

std.log adds the newline for you. std.log.debug messages only show in debug builds: built with -O fast (or -O safe), this program prints the first three lines only. That makes std.log a good fit for messages you want while developing and don’t want to delete later.

You want to… Use
Learn, experiment, debug something quickly std.debug.print
Print a program’s real results a buffered stdout writer, then flush
Print one fixed line to stdout std.Io.File.stdout().writeStreamingAll(io, "...")
Log progress, warnings and errors std.log.info / warn / err

Zig Readers & Writers goes further with writers (files, memory, your own types), and Zig Io Interface explains what Io is and why Zig passes it around.

Print the squares of 1 to 5 to stdout, one per line, like 3 squared is 9. Use a buffered writer.

Hint: use for (1..6) |n| { ... } to loop from 1 to 5 (the end is not included), and remember flush.

Show solution
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;
for (1..6) |n| {
try out.print("{d} squared is {d}\n", .{ n, n * n });
}
try out.flush();
}

Output:

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

All five lines collect in the buffer and go out together at flush. Loops get their own lesson in Zig For.

This program should print a goodbye message, but prints nothing. Fix it:

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

Hint: the text is in the buffer. What sends it out?

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
var buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer);
const out = &stdout_writer.interface;
try out.print("Goodbye, {s}!\n", .{"for now"});
try out.flush();
}

Output:

Goodbye, for now!

Without flush, the text stays in the buffer and is lost when the program ends.

Write a program that adds 19 and 23. Send the note adding the numbers... to stderr with std.debug.print, and the result 42 to stdout.

Hint: use std.debug.print for the note and out.print (plus flush) for the result.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
var buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer);
const out = &stdout_writer.interface;
std.debug.print("adding the numbers...\n", .{});
try out.print("{d}\n", .{19 + 23});
try out.flush();
}

Output:

adding the numbers...
42

In a terminal you see both lines. If you build it and run ./add > result.txt, only the note shows on screen and result.txt contains just 42.

  • Programs have two output streams: stdout for results and stderr for messages. > and | only take stdout.
  • std.debug.print writes to stderr, needs no setup and can’t fail. Use it for learning and debugging.
  • For stdout, main takes init: std.process.Init and returns !void, and writing uses init.io and try.
  • writeStreamingAll writes plain text. A buffered writer (.writer(io, &buffer) then .interface) gives you print.
  • Buffers turn many small writes into a few big ones, but you must flush at the end, or output goes missing.
  • std.log writes labelled messages to stderr, and hides debug messages in release builds.

Next up: Zig Format Strings, every {} placeholder and how to control width, padding and precision.

Quick check

1. Where does std.debug.print write its text?
2. A program prints with a buffered stdout writer, but nothing appears. What's the most likely cause?
3. Why does a main that writes to stdout return !void?
4. You run ./report > out.txt. Which output ends up in out.txt?