#Best way to read a file into a buffer?
1 messages · Page 1 of 1 (latest)
not sure what you mean by the first one
for the second one, it doesn't matter, no
and by the way, you can specify the maximum amount to read from the file
so you don't end up allocating bajillions
is there an easy way to get the length of the file? Excluding the header and metadata and stuff?
yes
std.fs.File.seekFromEnd(0);
std.fs.File.getPos();
should tell you the exact size in bytes of a file's contents
that's only after you've opened it though
you can also stat() it
yes actually I just see that getEndPos() does that
didn't realize there was a dedicated function for that
you can just do const sizeInBytes = try file.getEndPos(); then
const cwd: std.fs.Dir = std.fs.cwd();
const file = try cwd.openFile("input.txt", .{});
defer file.close();
// const fba = std.heap.FixedBufferAllocator.init(&mem);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = gpa.allocator();
defer gpa.deinit();
const buf = try file.readToEndAlloc(alloc, try file.getEndPos());
It's erroring out on the defer
well what's the error
and there's 2 defers
you probably need to do defer _ = gpa.deinit();
since I am guessing the error is a compile error for an unused return value
such is the way of using low level code
tis a difficult path...
idk what happened though, if the code does what I think it does then the buffer should just be the file contents and nothing more
so idk why it would leak memory. maybe I need to free the iterator?