I was trying to understand the example 13-errors-catch.zig in the official zig overview ( Overview ⚡ Zig Programming Language )
const std = @import("std");
pub fn main() void {
const file: std.fs.File = std.fs.cwd().openFile("does_not_exist/foo.txt", .{}) catch |err| label: {
std.debug.print("unable to open file: {}\n", .{err});
break :label .stderr();
};
file.writeAll("all your codebase are belong to us\n") catch return;
}
This is of course an example of the use of catch, and that when an error occurs in opening the file, that the result of .stderr() is assigned to file.
However assuming that the directory does_not_exist would actually exist:
- is that
fileopened for reading and writing? - should the opened file be closed (
defer file.close())? - how bad would it be to close the stderr output? ( I remember in early Unix systems (ie. 80’s), this could screw up the terminal).