Print:
pub fn main(init: std.process.Init) !void {
// In order to do I/O operations need an `Io` instance.
const io = init.io;
// print 1
var stdout_buffer: [1024]u8 = undefined;
var stdout_file_writer = std.Io.File.Writer.init(std.Io.File.stdout(), io, &stdout_buffer);
const stdout_writer = &stdout_file_writer.interface;
try stdout_writer.print("this is a {s} string\n", .{"print 1"});
try stdout_writer.flush(); // Don't forget to flush!
// print 2
const arena: std.mem.Allocator = init.arena.allocator();
const out = try std.fmt.allocPrint(arena, "this is a {s} string\n", .{"print 2"});
defer arena.free(out);
try std.Io.File.stdout().writeStreamingAll(init.io, out);
// print 3
var buffer: [1024]u8 = undefined;
var writer = std.Io.File.stdout().writer(init.io, &buffer);
var stdout = &writer.interface;
const a_string = try std.fmt.allocPrint(arena, "{s}", .{"print 3"});
defer arena.free(out);
try stdout.print("this is a {s} string\n", .{a_string});
try writer.flush();
// OUTPUT:
// this is a print 1 string
// this is a print 2 string
// this is a print 3 string
} print in zig
Read file content:
// create file
const dst_file = "/tmp/created.txt";
const file_created = try std.Io.Dir.cwd().createFile(init.io, dst_file, .{ .read = true });
defer file_created.close(init.io);
// populate file
const created_file_content = "foo bar baz\n";
try std.Io.File.writeStreamingAll(file_created, init.io, created_file_content);
// read file content
var stdin_buf: [1024]u8 = undefined;
const file = try std.Io.Dir.cwd().openFile(init.io, dst_file, .{});
var reader = file.reader(init.io, &stdin_buf);
const stdin_read_1 = &reader.interface;
const len = try file.length(init.io);
const content = try stdin_read_1.readAlloc(arena, len);
defer arena.free(content);
std.debug.print("{s}\n", .{content});
// OUTPUT: foo bar baz file create, write, read
List entries:
// list entries in directory
var dir_to_iter = try std.Io.Dir.cwd().openDir(init.io, "/tmp", .{
.iterate = true,
});
defer dir_to_iter.close(init.io);
var iter = dir_to_iter.iterate();
while (try iter.next(init.io)) |entry| {
std.debug.print("entry: {s}\n", .{entry.name});
} list entries