Zig Reading Input
Arguments and environment variables are fixed before your program starts. To ask a question while it runs, or to process data that another program pipes in, you read standard input (stdin). This page shows the Zig 0.17 way: a buffered reader, one line at a time with takeDelimiter, a clean stop at the end of input, and the one mistake that makes interactive programs look frozen.
Where stdin comes from
Section titled “Where stdin comes from”Every program has one input stream next to its two output streams. Where it comes from depends on how you start the program:
./app # stdin is your keyboard: you type, Enter sends a lineecho "Ada" | ./app # stdin is the output of another program./app < names.txt # stdin is a fileYour program reads it the same way in all three cases. And in all three, the input eventually ends. With a pipe or a file, that happens when the data runs out. At the keyboard, you end it yourself with Ctrl+D on Linux and macOS, or Ctrl+Z then Enter on Windows. Handling that end cleanly is part of reading input well.
Reading one line
Section titled “Reading one line”Reading works a lot like the buffered writer from Zig Output, in reverse: you give the reader a buffer, and it fills that buffer from stdin in big chunks.
const std = @import("std");
pub fn main(init: std.process.Init) !void { var stdin_buffer: [1024]u8 = undefined; var stdin_reader = std.Io.File.stdin().reader(init.io, &stdin_buffer); const stdin = &stdin_reader.interface;
const line = try stdin.takeDelimiter('\n') orelse { std.debug.print("no input\n", .{}); return; }; std.debug.print("you said: {s}\n", .{line});}echo "hello there" | ./echo1./echo1 < /dev/nullYou’ll see:
you said: hello thereno inputHere’s what each piece does:
stdin_bufferis room for 1024 bytes. As you’ll see below, it’s also the longest line this reader can handle.std.Io.File.stdin().reader(init.io, &stdin_buffer)makes a reader for stdin that uses that buffer.&stdin_reader.interfacegets the general-purpose reader, a*std.Io.Reader. All the reading functions live there, and they work the same on files, network sockets and memory.stdin.takeDelimiter('\n')reads up to the next newline and gives you the line without the\n.
takeDelimiter returns !?[]u8: it can fail (an error), and it can return null, which means the input has ended. try ... orelse { ... } handles both: try passes errors up, and orelse runs its block when there’s no line. /dev/null is an input that’s empty from the start, so the program gets null straight away.
Flush your prompt before you wait
Section titled “Flush your prompt before you wait”Now an interactive version that asks a question. It prints the prompt to stdout with a buffered writer. This version has a bug:
const std = @import("std");
pub fn main(init: std.process.Init) !void { var out_buffer: [256]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(init.io, &out_buffer); const out = &stdout_writer.interface;
var in_buffer: [256]u8 = undefined; var stdin_reader = std.Io.File.stdin().reader(init.io, &in_buffer); const in = &stdin_reader.interface;
try out.writeAll("What's your name? "); const name = try in.takeDelimiter('\n') orelse ""; try out.print("Hi, {s}!\n", .{name}); try out.flush();}Run it in a terminal and the cursor just sits on an empty line. No question. If you guess that it wants a name and type Ada, you’ll see:
AdaWhat's your name? Hi, Ada!The prompt was sitting in the output buffer the whole time, waiting for a flush. Meanwhile the program was already waiting for input. The fix is one line: flush right after the prompt, before you read.
const std = @import("std");
pub fn main(init: std.process.Init) !void { var out_buffer: [256]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(init.io, &out_buffer); const out = &stdout_writer.interface;
var in_buffer: [256]u8 = undefined; var stdin_reader = std.Io.File.stdin().reader(init.io, &in_buffer); const in = &stdin_reader.interface;
try out.writeAll("What's your name? "); try out.flush(); // show the question now
const line = try in.takeDelimiter('\n') orelse ""; const name = std.mem.trim(u8, line, " \t\r");
try out.print("Hi, {s}!\n", .{name}); try out.flush();}Now the question shows up first, you type on the same line, and you’ll see:
What's your name? AdaHi, Ada!Trim what people type
Section titled “Trim what people type”Notice the std.mem.trim(u8, line, " \t\r") in the fixed version. It removes spaces, tabs and \r from both ends of the line. You want this almost every time you read typed input:
- People add spaces by accident, and
" 42"is not a number toparseInt. - On Windows, lines end with
\r\n.takeDelimiter('\n')stops at the\nand leaves the\rat the end of your line, so"yes\r"isn’t equal to"yes". The same happens on any system when you read a file that was saved on Windows.
trim doesn’t copy anything. It returns a smaller slice of the same bytes.
Reading every line until the end
Section titled “Reading every line until the end”Most programs that read stdin read all of it, one line at a time. Because takeDelimiter returns null at the end, a while with a capture is a perfect fit (the reference calls it while with optionals):
const std = @import("std");
pub fn main(init: std.process.Init) !void { var stdin_buffer: [1024]u8 = undefined; var stdin_reader = std.Io.File.stdin().reader(init.io, &stdin_buffer); const stdin = &stdin_reader.interface;
var count: usize = 0; while (try stdin.takeDelimiter('\n')) |line| { count += 1; std.debug.print("{d}: {s}\n", .{ count, line }); } std.debug.print("read {d} lines\n", .{count});}printf 'apple\nbanana\n\ncherry' | ./numberYou’ll see:
1: apple2: banana3:4: cherryread 4 linesTwo details worth knowing, both visible here:
- An empty line comes back as an empty string
"", notnull. Only the real end of input isnull. That’s why line 3 is empty instead of the loop stopping early. - The last line doesn’t need a newline.
cherryhas no\nafter it, and you still get it.
Write it against a reader, test it with a string
Section titled “Write it against a reader, test it with a string”Here’s a habit that pays off quickly. Put the logic in a function that takes a *std.Io.Reader instead of creating the stdin reader inside it. In main you pass the stdin reader. Anywhere else, like a test, you pass a reader over a plain string with std.Io.Reader.fixed(...):
const std = @import("std");
const Totals = struct { sum: i64 = 0, numbers: usize = 0, skipped: usize = 0,};
fn sumLines(in: *std.Io.Reader) !Totals { var totals: Totals = .{}; while (try in.takeDelimiter('\n')) |raw| { const line = std.mem.trim(u8, raw, " \t\r"); if (line.len == 0) continue; // ignore blank lines
const n = std.fmt.parseInt(i64, line, 10) catch { std.debug.print("skipping '{s}': not a number\n", .{line}); totals.skipped += 1; continue; }; totals.sum += n; totals.numbers += 1; } return totals;}
pub fn main() !void { var in: std.Io.Reader = .fixed("10\n 20 \nabc\n\n-5\r\n7"); const t = try sumLines(&in); std.debug.print("{d} numbers, sum {d}, {d} skipped\n", .{ t.numbers, t.sum, t.skipped });}Output:
skipping 'abc': not a number4 numbers, sum 32, 1 skippedThat one test string covers spaces, a bad line, a blank line, a Windows \r\n ending and a last line without a newline, without typing anything. In the real program, main makes the stdin reader and calls sumLines(&stdin_reader.interface). The function doesn’t know or care where the bytes come from; that’s the whole point of the std.Io.Reader interface (Zig Readers & Writers goes deeper).
The parsing part is the same std.fmt.parseInt as in Zig Command-Line Arguments. The difference is what to do with bad input: for a stream of data, skipping and reporting a bad line is often friendlier than stopping.
The line is borrowed, not yours
Section titled “The line is borrowed, not yours”The slice takeDelimiter returns points into the reader’s buffer. The next read reuses that buffer, so the old slice can end up showing different bytes. This program tries to keep the lines in a list:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var stdin_buffer: [64]u8 = undefined; var stdin_reader = std.Io.File.stdin().reader(init.io, &stdin_buffer); const in = &stdin_reader.interface;
var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(gpa);
while (try in.takeDelimiter('\n')) |line| { try lines.append(gpa, line); // bug: keeps a borrowed slice }
for (lines.items) |line| std.debug.print("[{s}]\n", .{line});}Type first, second and third, then press Ctrl+D, and you’ll see something like:
[third][third][third]Every saved slice points at the same buffer, and by the end that buffer holds the last line. (Pipe the input in all at once and it might even look right, which makes this bug extra sneaky.) If you want to keep a line after the next read, copy it:
try lines.append(gpa, try gpa.dupe(u8, line));Then free each copy when you’re done with the list (or use an arena and free everything at once). If you only use the line inside the loop body, like every other example on this page, no copy is needed.
Lines longer than the buffer
Section titled “Lines longer than the buffer”The reader needs the whole line in its buffer to find the newline. A line longer than the buffer fails with error.StreamTooLong. With a 1024-byte buffer and a 3000-character line, the line-numbering program above stops with:
error: StreamTooLongSo pick a buffer size that fits the longest line you’re willing to accept. A few KB is plenty for typed input and most text files. If a long line should be skipped instead of stopping the program, catch the error:
const maybe_line = in.takeDelimiter('\n') catch |err| switch (err) { error.StreamTooLong => { std.debug.print("line too long, stopping\n", .{}); return; }, else => |e| return e,};Reading everything at once
Section titled “Reading everything at once”Sometimes you don’t want lines, you want the whole input as one string, for example to parse it as JSON. allocRemaining reads until the end and allocates the result:
const std = @import("std");
pub fn main(init: std.process.Init) !void { var stdin_buffer: [4096]u8 = undefined; var stdin_reader = std.Io.File.stdin().reader(init.io, &stdin_buffer);
const all = try stdin_reader.interface.allocRemaining(init.gpa, .limited(1024 * 1024)); defer init.gpa.free(all);
std.debug.print("read {d} bytes\n", .{all.len});}printf 'hello\nworld\n' | ./slurpYou’ll see:
read 12 bytesThe .limited(1024 * 1024) is a safety limit: if someone pipes in more than that, you get error.StreamTooLong instead of your program trying to eat all the memory. You own the result, so free it.
Putting it together: a guessing game
Section titled “Putting it together: a guessing game”Here’s a small interactive program that uses everything: a prompt with a flush, reading a line, trimming, parsing, a retry for bad input, and a clean exit at the end of input.
const std = @import("std");
pub fn main(init: std.process.Init) !void { const secret: u32 = 37;
var out_buffer: [256]u8 = undefined; var stdout_writer = std.Io.File.stdout().writer(init.io, &out_buffer); const out = &stdout_writer.interface;
var in_buffer: [256]u8 = undefined; var stdin_reader = std.Io.File.stdin().reader(init.io, &in_buffer); const in = &stdin_reader.interface;
var tries: u32 = 0; while (true) { try out.writeAll("Guess a number from 1 to 100: "); try out.flush();
const raw = try in.takeDelimiter('\n') orelse { try out.writeAll("\nBye!\n"); break; }; const guess = std.fmt.parseInt(u32, std.mem.trim(u8, raw, " \t\r"), 10) catch { try out.writeAll("That's not a number, try again.\n"); continue; };
tries += 1; if (guess < secret) { try out.writeAll("Too low.\n"); } else if (guess > secret) { try out.writeAll("Too high.\n"); } else { try out.print("Yes! {d} it is, in {d} tries.\n", .{ secret, tries }); break; } } try out.flush();}A session in the terminal looks like this:
Guess a number from 1 to 100: 50Too high.Guess a number from 1 to 100: abcThat's not a number, try again.Guess a number from 1 to 100: 25Too low.Guess a number from 1 to 100: 37Yes! 37 it is, in 3 tries.Press Ctrl+D instead of guessing and it prints Bye! and ends normally. A real game would pick a random secret; Zig Next Steps has ideas for growing small programs like this one.
Practice
Section titled “Practice”1. Shout it back
Section titled “1. Shout it back”Write a program that reads lines from stdin until the end and prints each one in UPPERCASE.
Hint: std.ascii.upperString(&buf, line) copies line into buf in uppercase and returns the filled part. Make buf as big as your reader’s buffer.
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void { var stdin_buffer: [1024]u8 = undefined; var stdin_reader = std.Io.File.stdin().reader(init.io, &stdin_buffer); const in = &stdin_reader.interface;
var upper: [1024]u8 = undefined; while (try in.takeDelimiter('\n')) |line| { std.debug.print("{s}\n", .{std.ascii.upperString(&upper, line)}); }}printf 'hello\nzig is fun\n' | ./shoutYou’ll see:
HELLOZIG IS FUNA line can’t be longer than the reader’s 1024-byte buffer, so a 1024-byte upper buffer is always big enough.
2. Count words
Section titled “2. Count words”Write countWords(in: *std.Io.Reader) !usize that counts the words in all lines (words are separated by spaces), and test it with std.Io.Reader.fixed.
Hint: std.mem.tokenizeScalar(u8, line, ' ') gives you the words of a line one by one with next(), and it skips repeated spaces for you.
Show solution
const std = @import("std");
fn countWords(in: *std.Io.Reader) !usize { var words: usize = 0; while (try in.takeDelimiter('\n')) |line| { var it = std.mem.tokenizeScalar(u8, line, ' '); while (it.next()) |_| words += 1; } return words;}
pub fn main() !void { var in: std.Io.Reader = .fixed("the quick brown fox\n\njumps over\nthe lazy dog\n"); std.debug.print("{d} words\n", .{try countWords(&in)});}Output:
9 wordsThe double space between quick and brown and the empty line don’t produce empty “words”, because tokenizeScalar skips empty pieces. In main you’d call countWords(&stdin_reader.interface) to count real input.
- stdin can be the keyboard, a pipe or a file. Your program reads it the same way, and it always ends eventually (Ctrl+D or Ctrl+Z at the keyboard).
- Make a reader with
std.Io.File.stdin().reader(io, &buffer)and use its.interface. The buffer size is your longest allowed line. takeDelimiter('\n')returns the next line without the newline,""for an empty line, andnullat the end. Loop withwhile (try in.takeDelimiter('\n')) |line|.- Flush your prompt before reading, or the question stays stuck in the output buffer.
- Trim typed lines (
" \t\r"), and copy a line withdupeif you need it after the next read. - Write input-handling code against
*std.Io.Readerand test it withstd.Io.Reader.fixed("...").
Next up: Zig File I/O, reading and writing files and folders with std.Io.Dir.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- I/O as an interface (0.16 release notes): why readers and writers take an
Iovalue, introduced in 0.16 and still the way in 0.17. - GenericReader, AnyReader and FixedBufferStream removed (0.16 release notes): the move to
std.Io.ReaderandReader.fixed, useful when you read older Zig code. whilewith optionals in the 0.17.1 reference: the loop shape you use for reading lines.- Standard library docs (0.17.1): look up
std.Io.ReaderfortakeDelimiter,allocRemainingand the othertakeandpeekfunctions.