Managing file reading, closing + buffer allocation and deallocation

How about this:

fn readFile(fname: []const u8, alloc8r: std.mem.Allocator) !void
{
    var buf: []u8 = blk: {
        const f = try std.fs.cwd().openFile(fname, .{});
        defer f.close(); // The file will be closed when we leave the block, which is great

        const f_len = try f.getEndPos(); 
        const _b =  try alloc8r.alloc(u8, f_len);
        errdefer alloc8r.free(_b); // Will be active until the block ends
        const read_bytes = try f.readAll(buf);
        std.debug.print("Read {} bytes\n", .{read_bytes});
        break :blk  _b;
    };
    defer alloc8r.free(buf);

    // Work with `buf`, it will be freed when we leave the function, whether normally, or by returning an error
}

Please note use of break to return from the labeled block.

5 Likes