#Can I check if a file exists without opening it?

1 messages · Page 1 of 1 (latest)

robust wren
#

Hi, I have this function

fn hasGitIgnore(absolute_path: []const u8) bool {
    const file_name = if (absolute_path[absolute_path.len - 1] == '/') ".gitignore" else "/.gitignore";

    var buf: [255]u8 = undefined;
    const gitIgnorePath = std.fmt.bufPrint(&buf, "{s}{s}", .{ absolute_path, file_name }) catch "";

    var file = std.fs.openFileAbsolute(gitIgnorePath, .{}) catch {
        return false;
    };
    defer file.close();

    return true;
}

It's currently using openFileAbsolute to check if the file exists.
Is there a better way to do this?
I've heard about Dir.access, but the purpose of this function requires taking in a string, not a Dir 🤔

wraith pike
#
var dir = std.fs.openDirAbsolute(absolute_path, .{});
defer dir.close();
dir.access(".gitignore", .{}) catch return false;
return true;
#

with std.fs, you don't really have to construct paths

robust wren
#

is opening a file more costly than opening a dir?

#

if so thank you for the solution

wraith pike
#

access is generally faster if you just want to check for the access

#

you can pass the dir handle along to many functions if you operate on the same dir

#

you should generally avoid paths (and especially absolute paths)

robust wren
#

thank you for the advice ❤️

lusty mica
#

Keep in mind that there can be TOCTOU issues with stuff like this

#

Which is why there's not a does_exist() proc

#

e.g: You do the check, and then someone immediately creates the file, and then your program continues