#Checking if file exists and creating if not

1 messages · Page 1 of 1 (latest)

foggy garnet
#

Could I get a quick sanity check on this? Thanks.

    const agent_file = fs.openFileAbsolute(agent_path, .{ .mode = .read_only }) catch |err| switch (err) {
        error.FileNotFound => blk: {
            const file = try fs.createFileAbsolute(agent_path, .{});
            errdefer file.close();
            try file.writeAll(y3_plist);
            log.info("y3 service installed: {s}", .{agent_path});
            break :blk file;
        },
        else => {
            log.err("failed to open {s}: {s}", .{ agent_path, @errorName(err) });
            return err;
        },
    };
    defer agent_file.close();
floral solar
#

std.fs.cwd().createFile(path, .{ ... })

#

The create in the name means that it will create it if it doesn't exist.

#

Whereas the open versions error in that case.

foggy garnet
#

oh and i don't need to capture the happy path, edited

foggy garnet
visual juniper
stiff plank
#

fyi .truncate = false won't append

#

you'll need to seek to the end of the file manually

foggy garnet
#

so if I don't want to modify a file that already exists, open first is the correct approach?