What is the easiest way to check if a file exists in zig?
As part of my build process, I need to avoid writing over a file if it already exists.
I have seen std.fs.access
but I'm not sure if there is an easier way.
Yes, the std.fs.Dir.access
is the one you should use. But for your case, you might want to create the file with the exclusive=true
flag and handle the PathAlreadyExists
error as recommended in the std.fs.Dir.access
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.
For example:
const std = @import("std");
pub fn main() !void {
try write_cache_file();
}
fn write_cache_file() !void {
var file = std.fs.cwd().createFile("file.tmp", .{ .exclusive = true }) catch |e|
switch (e) {
error.PathAlreadyExists => {
std.log.info("already exists", .{});
return;
},
else => return e,
};
defer file.close();
std.log.info("write file here", .{});
}
This prints:
$ zig build run
info: write file here
$ zig build run
info: already exists