Skip to content

Instantly share code, notes, and snippets.

@ssteinbach
Created September 3, 2025 22:55
Show Gist options
  • Select an option

  • Save ssteinbach/47edaf4d72160c855e7dd3b9ec02b183 to your computer and use it in GitHub Desktop.

Select an option

Save ssteinbach/47edaf4d72160c855e7dd3b9ec02b183 to your computer and use it in GitHub Desktop.
//! example of opening a file and writing to it with a writer (0.15.1+)
const std = @import("std");
pub fn some_child_fn(
writer: *std.io.Writer,
) !void
{
try writer.print("write from child_fn\n", .{});
}
test "open a file and use a writer to write stuff to it"
{
// write directly
const fpath = "/var/tmp/test.txt";
var outfile = try std.fs.cwd().createFile(
fpath,
.{},
);
defer outfile.close();
// write via writer object
var buf:[1024]u8 = @splat(0);
var writer_root = outfile.writer(&buf);
const writer = &writer_root.interface;
try writer.print("Hello, {s}\n", .{ "first line" });
// pass to child
try some_child_fn(writer);
try writer.flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment