(originally posted here: https://zig.news/liyu1981/tmpfilezig-an-reusable-utility-for-using-tmp-files-in-sys-tmp-1l63)
As titled, a simple but convenient lib for creating tmp dir/tmp file in system tmp folder.
So far I can not found in std
about how to do this. There is one std.testing.TmpDir
, and after reading the src code, it actually creates the tmp files in zig-cache
(which makes sense). Then how about the usual task of creating tmp files in system tmp folder like /tmp
?
So here is tmpfile.zig
{% embed https://github.com/liyu1981/tmpfile.zig %}
Simple usage is like
var tmp_dir = try ThisModule.tmpDirOwned(.{});
defer {
tmp_dir.deinit();
tmp_dir.allocator.destroy(tmp_dir);
}
var tmp_file = try tmpfile.tmpFile(.{ .tmp_dir = tmp_dir });
defer tmp_file.deinit();
try tmp_file.f.writeAll("hello, world!");
try tmp_file.f.seekTo(0);
var buf: [4096]u8 = undefined;
var read_count = try tmp_file.f.readAll(&buf);
try testing.expectEqual(read_count, "hello, world!".len);
try testing.expectEqualSlices(u8, buf[0..read_count], "hello, world!");
var tmp_file2 = try tmpfile.tmpFile(.{ .tmp_dir = tmp_dir });
defer tmp_file2.deinit();
try tmp_file2.f.writeAll("hello, world!2");
try tmp_file2.f.seekTo(0);
read_count = try tmp_file2.f.readAll(&buf);
try testing.expectEqual(read_count, "hello, world!2".len);
try testing.expectEqualSlices(u8, buf[0..read_count], "hello, world!2");
It can be used as normal zig
packages, or used in build.zig
file as it has exposed itself. Or simply you can just copy the tmpfile.zig
file over for using it. It is a simple util, so make it simle with your project :).