是的,这std.fs.Dir.access就是您应该使用的。但对于您的情况,您可能需要创建带有标志的文件exclusive=true并PathAlreadyExists按照std.fs.Dir.access 文档中的建议处理错误:
使用此函数时请注意检查时间和使用时间竞争条件。例如,不必测试文件是否存在然后打开它,而是打开它并处理找不到文件的错误。
例如:
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", .{});
}
Run Code Online (Sandbox Code Playgroud)
这打印:
$ zig build run
info: write file here
$ zig build run
info: already exists
Run Code Online (Sandbox Code Playgroud)