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);
errdefer alloc8r.free(buf);
const read_bytes = try f.readAll(buf);
std.debug.print("Read {} bytes\n", .{read_bytes});
break :blk buf;
};
defer alloc8r.free(contents);
// 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));
defer allocator.free(contents);
4 Likes
@squeek502 : you are late to the party
1 Like
It’s not that i don’t like the block. I don’t like
- Having
undefined
variables. This is solved by thebreak
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. - Having to juggle
defer
/errdefer
statements, but I guess this can’t be avoided.
Thank you for posting!