Check file existence
In this example, access
is utilized to verify file existence; however, for it to function correctly, one must specifically check for the FileNotFound
error type.
//! Test file/directory existence
const std = @import("std");
const fs = std.fs;
pub fn main() !void {
const filename = "build.zig";
var found = true;
fs.cwd().access(filename, .{}) catch |e| switch (e) {
error.FileNotFound => found = false,
else => return e,
};
std.debug.assert(found);
}
However, there is a gotcha described in its documentation:
Be careful of Time-Of-Check-Time-Of-Use race conditions when using this function. For example, instead of testing if a file exists and then opening it, just open it and handle the error for file not found.