Printing to stdout and reading lines from stdin are the most common I/O operations in CLI programs, yet they currently require several lines of ceremony. It would be great to avoid that and instead add four helper functions to “Io”:
pub fn print(io: Io, comptime fmt: []const u8, args: anytype) File.Writer.Error!void {
var buf: [1024]u8 = undefined;
var w = File.stdout().writer(io, &buf);
try w.interface.print(fmt, args);
try w.flush();
}
pub fn println(io: Io, comptime fmt: []const u8, args: anytype) File.Writer.Error!void {
try io.print(fmt ++ "\n", args);
}
pub const ReadLineError = File.Reader.Error || error{StreamTooLong};
pub fn readLine(io: Io, buffer: []u8) ReadLineError!?[]const u8 {
var r = File.stdin().reader(io, buffer);
const line = (try r.interface.takeDelimiter('\n')) orelse return null;
return std.mem.trimRight(u8, line, "\r");
}
pub fn readAlloc(io: Io, gpa: Allocator, limit: Limit) LimitedAllocError![]u8 {
var r = File.stdin().reader(io, &.{});
return r.interface.allocRemaining(gpa, limit);
}
And the example:
pub fn main(init: std.process.Init) !void {
try init.io.println("Hello, World!");
var line_buf: [4096]u8 = undefined;
if (try init.io.readLine(&line_buf)) |line| {
try init.io.println("echo: {s}", .{line});
}
}