People said the new std.Io are great,but ,how to use?I want to know how to use it to print worlds to stdout。How do you use it to open files,read files? how to write worlds to files? by new great great great std.Io?
So you have std.Io.File. You can use it to open files, write files (via std.Io.File.Writer) etc.
And most operations in std.Io.File take an io argument which is the std.Io interface of your choice.
Right now, the “juicy main” is already a thing, so you can write pub fn main(init: std.process.Init). You already have an std.Io instance here, via init.io.
And then you can just, for example, create a buffer for stdout (where your output will be stored before being printed if it is short enough), create a file writer that writes to the stdout file handle (which takes your std.Io instance as argument), get the writer interface and then print into that writer (and don’t forget to flush!).
So it will look something like this:
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
var stdout_buffer: [1024]u8 = undefined;
var stdout_file_writer: std.Io.File.Writer = .init(.stdout(), io, &stdout_buffer);
// IMPORTANT: CONSTANT "writer" with POINTER to interface; else you have some memory corruption
const stdout_writer = &stdout_file_writer.interface;
try stdout_writer.print("hello {s}\n", .{"world"});
try stdout_writer.flush();
}
For opening files, you use std.Io.Dir and then call openFile (it’s in there). For the current Dir, you can just use .cwd().
const std = @import("std");
const Init = std.process.Init;
const Io = std.Io;
// `Init` contains a bunch of useful things
// a general purpose allocator, an arena allocator, an Io, etc
// it is also the only way to get args and env variables now
pub fn main(init: Init) !void {
var stdout = Io.File.stdout().writer(init.io, &.{});
try stdout.interface.writeAll("hello world");
// flush is unecessary since the writer was given a 0 length buffer
}
pub fn main(init: Init) !void {
try std.Io.File.stdout().writeStreamingAll(init.io, "Hello, World!\n");
}
const std = @import("std");
const Init = std.process.Init;
more examples in https://codeberg.org/ziglang/zig/pulls/30644
thanks. I learned
I didn’t notice document has already been updated for this.
![]()