Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Zig Dictionary
  3. std.io.getStdOut() / Writer

std.io.getStdOut() / Writer

In Zig, you obtain a standard output file with std.io.getStdOut(), then call .writer() to get a Writer or .reader() to get a Reader. With a Writer, you can write to standard output using methods such as print() and writeAll(). You can also obtain a Reader for standard input via std.io.getStdIn() to read keyboard input from the user. This page covers the syntax, usage, and practical examples of low-level I/O using Writer and Reader.

Syntax

// -----------------------------------------------
// Getting a Writer for standard output
// -----------------------------------------------

const stdout = std.io.getStdOut().writer();
// std.io.getStdOut() : Returns a File struct representing standard output
// .writer()          : Obtains a Writer (std.fs.File.Writer type) from the File

try stdout.print("format string\n", .{});
// print() : Writes formatted output. Requires try because it can return an error

try stdout.writeAll("string\n");
// writeAll() : Writes a string as-is without any formatting

// -----------------------------------------------
// Getting a Reader for standard input
// -----------------------------------------------

const stdin = std.io.getStdIn().reader();
// std.io.getStdIn() : Returns a File struct representing standard input
// .reader()         : Obtains a Reader (std.fs.File.Reader type) from the File

var buf: [256]u8 = undefined;
// readUntilDelimiterOrEof() : Reads until the specified byte or EOF
// Returns ?[]u8; returns null at EOF
const line = try stdin.readUntilDelimiterOrEof(&buf, '\n');

// -----------------------------------------------
// Getting a Writer for standard error
// -----------------------------------------------

const stderr = std.io.getStdErr().writer();
// std.io.getStdErr() : Returns a File struct representing standard error
try stderr.print("error message\n", .{});

Syntax Reference

Syntax / MethodDescription
std.io.getStdOut()Returns a std.fs.File representing standard output.
std.io.getStdIn()Returns a std.fs.File representing standard input.
std.io.getStdErr()Returns a std.fs.File representing standard error.
.writer()Obtains a Writer from a File. Provides write methods such as print() and writeAll().
.reader()Obtains a Reader from a File. Provides read methods such as readUntilDelimiterOrEof().
writer.print(fmt, args)Writes formatted output to standard output. Requires try because it can return an error.
writer.writeAll(str)Writes a string as-is without any formatting.
reader.readUntilDelimiterOrEof(buf, delim)Reads until the specified delimiter or EOF. Returns ?[]u8.
reader.readUntilDelimiter(buf, delim)Reads until the specified delimiter. Returns an error if EOF is reached.
std.mem.trimRight(u8, slice, chars)Removes the specified characters from the end of a slice. Useful for stripping trailing newlines.

Sample Code

stdout_write.zig
// stdout_write.zig — sample for std.io.getStdOut() / getStdIn()
// Demonstrates how to use Writer/Reader for standard I/O
// using characters from Jujutsu Kaisen

// Import the standard library
const std = @import("std");

pub fn main() !void {
    // -----------------------------------------------
    // Get a Writer for standard output
    // -----------------------------------------------

    // Call getStdOut() to obtain the stdout File, then writer() to create a Writer.
    // All writes are performed through this Writer.
    const stdout = std.io.getStdOut().writer();

    // -----------------------------------------------
    // Formatted output with print()
    // -----------------------------------------------

    // print() takes a format string and a tuple of arguments.
    // try is required because the function can return an error.
    try stdout.print("=== Jujutsu Kaisen Sorcerer Roster ===\n", .{});
    try stdout.print("\n", .{});

    // Use {s} for strings and {d} for integers.
    const gojo_name = "Gojo Satoru";
    const gojo_grade = "Special Grade";
    const gojo_technique = "Limitless";
    try stdout.print("Name: {s}\n", .{gojo_name});
    try stdout.print("Grade: {s}\n", .{gojo_grade});
    try stdout.print("Technique: {s}\n", .{gojo_technique});
    try stdout.print("\n", .{});

    // -----------------------------------------------
    // Unformatted output with writeAll()
    // -----------------------------------------------

    // writeAll() writes a string directly without any format processing.
    // It is more efficient than print() when outputting a fixed string.
    try stdout.writeAll("--- Grade 1 Sorcerers ---\n");

    // -----------------------------------------------
    // List output using a struct and an array
    // -----------------------------------------------

    // Define a struct to hold sorcerer information.
    const Sorcerer = struct {
        name: []const u8,   // name
        grade: []const u8,  // grade
        cursed_energy: u32, // cursed energy level (placeholder value)
    };

    // Store Jujutsu Kaisen characters in an array.
    const sorcerers = [_]Sorcerer{
        .{ .name = "Gojo Satoru",   .grade = "Special Grade", .cursed_energy = 99999 },
        .{ .name = "Itadori Yuji",  .grade = "Grade 1",       .cursed_energy = 8800  },
        .{ .name = "Fushiguro Megumi", .grade = "Grade 1",    .cursed_energy = 7200  },
        .{ .name = "Kugisaki Nobara",  .grade = "Grade 1",    .cursed_energy = 6500  },
        .{ .name = "Nanami Kento",  .grade = "Grade 1",       .cursed_energy = 7800  },
    };

    // Iterate over the array with a for loop and print each sorcerer's info.
    for (sorcerers) |s| {
        try stdout.print("  {s} ({s}) Cursed Energy: {d}\n", .{ s.name, s.grade, s.cursed_energy });
    }
    try stdout.print("\n", .{});

    // -----------------------------------------------
    // Get and use a Writer for standard error
    // -----------------------------------------------

    // Call getStdErr() to obtain the stderr File.
    // Use it for error messages and debug information.
    const stderr = std.io.getStdErr().writer();
    try stderr.print("[debug] sorcerer count: {d}\n", .{sorcerers.len});

    // -----------------------------------------------
    // Get and use a Reader for standard input
    // -----------------------------------------------

    // Call getStdIn() to obtain the stdin File, then reader() to create a Reader.
    try stdout.writeAll("Enter a sorcerer name: ");

    const stdin = std.io.getStdIn().reader();

    // Prepare a buffer to hold the input.
    // Initializing with undefined avoids the cost of zero-initialization.
    var buf: [128]u8 = undefined;

    // readUntilDelimiterOrEof() reads until a newline ('\n').
    // The return type is ?[]u8; it is null at EOF.
    const maybe_input = try stdin.readUntilDelimiterOrEof(&buf, '\n');

    if (maybe_input) |raw| {
        // On Windows, a trailing '\r' may remain; trimRight() removes it.
        const input = std.mem.trimRight(u8, raw, "\r");
        try stdout.print("You entered: {s}\n", .{input});
    } else {
        try stdout.writeAll("(no input)\n");
    }

    try stdout.writeAll("\nDone.\n");
}
zig run stdout_write.zig
=== Jujutsu Kaisen Sorcerer Roster ===

Name: Gojo Satoru
Grade: Special Grade
Technique: Limitless

--- Grade 1 Sorcerers ---
  Gojo Satoru (Special Grade) Cursed Energy: 99999
  Itadori Yuji (Grade 1) Cursed Energy: 8800
  Fushiguro Megumi (Grade 1) Cursed Energy: 7200
  Kugisaki Nobara (Grade 1) Cursed Energy: 6500
  Nanami Kento (Grade 1) Cursed Energy: 7800

[debug] sorcerer count: 5
Enter a sorcerer name: Gojo Satoru
You entered: Gojo Satoru

Done.

How It Works

std.io.getStdOut() returns a std.fs.File representing standard output. Calling .writer() on it gives you a Writer, which provides methods such as print() and writeAll() for writing to standard output. print() performs formatted output, accepting a format string and a tuple of arguments. Because it can return an error, try is required. For fixed strings that need no formatting, writeAll() is simpler. To read from standard input, obtain a Reader with std.io.getStdIn().reader() and use readUntilDelimiterOrEof() to read one line into a buffer. The return type is ?[]u8 (an optional), so you unwrap it with if (maybe_input) |raw|. A Writer for error output is obtained the same way with std.io.getStdErr().writer(). For details on format specifiers, see std.debug.print() (debug output). For string operations, see String Basics.

If you find any errors or copyright issues, please .