Overview catch example, missing defer?

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:

  1. is that file opened for reading and writing?
  2. should the opened file be closed (defer file.close())?
  3. 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).
  1. Default mode is .read_only, see std.fs.Dir.openFile’s flags parameter.
  2. Yes, otherwise you might, for instance, hit the OS limit of how many file descriptors can be open at once. And if you choose to let the OS close all files automatically on process exit, there’s no guarantee of how soon those fds will actually be freed by the OS.
  3. Depends on the OS, but I doubt it can be catastrophic.
3 Likes

yeah this example is meant to showcase catching errors and doesn’t show full correct handing of all cases. it would probably not be a bad idea to change it so that it doesn’t involve file i/o at all

5 Likes

default mode is read only

files are os resources, the os should clean them up. doing them yourself is slower because they are individual syscalls, instead of a single (its not actually a syscall but close enough) you get by ending your program.

shouldn’t have any issues

1 Like