检查 Zig 中是否存在文件

tuk*_*ket 1 zig

检查 zig 中是否存在文件的最简单方法是什么?

作为构建过程的一部分,我需要避免覆盖已经存在的文件。

我见过std.fs.access,但我不确定是否有更简单的方法。

sig*_*god 5

是的,这std.fs.Dir.access就是您应该使用的。但对于您的情况,您可能需要创建带有标志的文件exclusive=truePathAlreadyExists按照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)