2

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.

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

I don't really want to open the file. The idea is if(!fileExists(filePath)) continueTheBuildProcess_and_copyTheResultingFile(filePath). Should I go with the access approach then?
@tuket yes. What else do you have in mind?
That's all, just wanted to be sure. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.