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).
Two places output can go
Section titled “Two places output can go”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
Section titled “std.debug.print writes to stderr”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 42You can see it go to stderr if you build the program and redirect its output:
zig build-exe answer.zig./answer > out.txtYou’ll see:
Starting...The answer is 42Both 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.
Writing to stdout
Section titled “Writing to stdout”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 handmainsome useful things when the program starts.init.iois theIovalue. (Zig Main & Init covers the rest.)std.Io.File.stdout()is the stdout stream, andwriteStreamingAll(io, text)writes all oftextto 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,
trypasses any error up, and!voidonmainmeans “returns nothing, but might return an error”. You’ll learn the details in Zig Errors. For now, puttryin front of anything that writes to stdout.
Formatted output with a buffered writer
Section titled “Formatted output with a buffered writer”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 = 4Line by line:
var buffer: [1024]u8 = undefined;makes room for 1024 bytes of text.undefinedmeans “I don’t care what’s in it yet”, since the writer will fill it.std.Io.File.stdout().writer(init.io, &buffer)creates a writer for stdout that uses that buffer.const out = &stdout_writer.interface;gets the general-purpose writer part. It’s of type*std.Io.Writer, and that’s what hasprint,writeAllandwriteByte. The sameprintworks for files, sockets and memory too.out.print(...)works just likestd.debug.print, but it puts the text into the buffer.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.
Why bother with a buffer?
Section titled “Why bother with a buffer?”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.
Don’t forget to flush
Section titled “Don’t forget to flush”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.
Mixing stdout and stderr
Section titled “Mixing stdout and stderr”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 stderr1. first, to stdout3. third, to stdoutLine 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.
Writing to stderr yourself, and std.log
Section titled “Writing to stderr yourself, and std.log”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 1warning: low on coffeeerror: something faileddebug: a detail only for debug buildsstd.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.
Which one should I use?
Section titled “Which one should I use?”| 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.
Practice
Section titled “Practice”1. A table of squares on stdout
Section titled “1. A table of squares on stdout”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 12 squared is 43 squared is 94 squared is 165 squared is 25All five lines collect in the buffer and go out together at flush. Loops get their own lesson in Zig For.
2. Where did my output go?
Section titled “2. Where did my output go?”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.
3. Results to stdout, notes to stderr
Section titled “3. Results to stdout, notes to stderr”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...42In 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.printwrites to stderr, needs no setup and can’t fail. Use it for learning and debugging.- For stdout,
maintakesinit: std.process.Initand returns!void, and writing usesinit.ioandtry. writeStreamingAllwrites plain text. A buffered writer (.writer(io, &buffer)then.interface) gives youprint.- Buffers turn many small writes into a few big ones, but you must
flushat the end, or output goes missing. std.logwrites labelled messages to stderr, and hidesdebugmessages in release builds.
Next up: Zig Format Strings, every {} placeholder and how to control width, padding and precision.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Hello World in the 0.17.1 reference: both official versions of Hello World, stdout and
std.debug.print. - I/O as an interface (0.16 release notes): why Zig passes an
Iovalue to everything that does input and output (introduced in 0.16, still the way in 0.17). - “Juicy main” (0.16 release notes): what
std.process.Initgives yourmain. - Standard library docs (0.17.1): look up
std.Io.Writerandstd.Io.Filefor every writer function.