wa-lang.org/wazero@v1.0.2/imports/wasi_snapshot_preview1/example/testdata/zig/cat.zig (about) 1 const std = @import("std"); 2 const io = std.io; 3 const os = std.os; 4 const allocator = std.heap.page_allocator; 5 const PreopenList = std.fs.wasi.PreopenList; 6 const stdout = std.io.getStdOut(); 7 const warn = std.log.warn; 8 9 pub fn main() !void { 10 // Allocate arguments from the the operating system. 11 const args = try std.process.argsAlloc(allocator); 12 defer std.process.argsFree(allocator, args); 13 14 // Pre-opened files are not available by default. When using WASI, you must 15 // manually initialize pre-opens to prevent openFile crashes. 16 // 17 // See https://ziglang.org/documentation/0.10.0/#WASI 18 var preopens = PreopenList.init(allocator); 19 defer preopens.deinit(); 20 try std.os.initPreopensWasi(allocator, "/"); 21 22 // loop on the args, skipping the filename (args[0]) 23 for (args[1..args.len]) |arg| { 24 25 // open the file from its absolute path, as "/" is pre-opened. 26 const file = std.fs.openFileAbsolute(arg, .{ .mode = .read_only }) catch |err| { 27 warn("Unable to open file {s}: {s}\n", .{ arg, @errorName(err) }); 28 return err; 29 }; 30 defer file.close(); 31 32 // Write the contents to stdout 33 stdout.writeFileAll(file, .{}) catch |err| { 34 warn("Unable to write contents to stdout: {s}\n", .{@errorName(err)}); 35 return err; 36 }; 37 } 38 }