Managing file reading, closing + buffer allocation and deallocation

Oops, I’m sorry, did not realized that at once.
But why do you want to close a file immediately after reading it’s content into a buffer?
Does working with the buffer take a lot of time in your case?
And you just do not want to hold resources associated with an open file?..

The option you say you don’t like (using a block to limit the scope of the defer) can be improved by using a labeled block:

fn readFile(fname: []const u8, alloc8r: std.mem.Allocator) !void
    const contents = blk: {
        const f = try std.fs.cwd().openFile(fname, .{});
        defer f.close();

        const f_len = try f.getEndPos();
        var buf = try alloc8r.alloc(u8, f_len);

        const read_bytes = try f.readAll(buf);
        std.debug.print("Read {} bytes\n", .{read_bytes});

        break :blk buf;

    // Work with `contents`

Note also that there is a std.fs.Dir function that will do what you want in one call:

const contents = try std.fs.cwd().readFileAlloc(allocator, file_path, std.math.maxInt(usize));

@squeek502 : you are late to the party :grinning:

1 Like

It’s not that i don’t like the block. I don’t like

  1. Having undefined variables. This is solved by the break statement, although I wish we didn’t have to use label if there’s just one block of code. I keep forgetting where the “:” goes in break statements… Oh well.
  2. Having to juggle defer / errdefer statements, but I guess this can’t be avoided.

Thank you for posting!