How to Open a folder or file and if it doesn't exists create the folder/file

So I’m working on a program that needs to open a folder and if the folder doesn’t exists it creates it, but I’m stuck as it is. this is my code.

pub fn setProjectHome(io: std.Io, env: *std.process.Environ.Map) !void {
    const home_env = env.get("HOME") orelse return error.NoHomeDirectory;
    const home_dir = try std.Io.Dir.openDirAbsolute(io, home_env, .{});
    defer home_dir.close(io);

    const zproj_dir = home_dir.openDir(io, ".config/zproj", .{}) catch |err| switch (err) {
        error.FileNotFound => home_dir.createDir(io, ".config/zproj", .default_dir) catch |create_err| switch (create_err) {
            error.PathAlreadyExists => std.debug.print("Project Path already exists", .{}),
            else => std.debug.print("Error: {any}", .{create_err}),
        },
        else => std.debug.print("Error: {any}", .{err}),
    };
    defer zproj_dir.close(io);

    const zproj_config_file = zproj_dir.openFile(io, "config.txt", .{}) catch |err| switch (err) {
        error.PathAlreadyExists => zproj_dir.createFile(io, "config.txt", .{}),
        else => std.debug.print("Error: {any}", .{err}),
    };
    defer zproj_config_file.close(io);

    var buffer: [1024]u8 = undefined;
    _ = try zproj_config_file.readPositionalAll(io, &buffer, 0);
}

I would like some help please and I’m also using zig 0.16 by the way. Thank you :folded_hands:

PS: You can ignore the buffer file part

What’s got you stuck, that seems sensible enough?

If not, may be best to simply “ensure” the directory exists first with a call to create and handle the error.

That’s what std.Io.Dir.createDirPathOpen is for. Create a directory if it does not already exist, and give you the directory handle for performing file operations inside it.

This is actually sensible. I’ve been coding for hours now. My brain feels like mush such that I didn’t see such an obvious answer :smiling_face_with_tear:

Thank you

Oh okay. Thank you very much