#reading a file in zig
1 messages · Page 1 of 1 (latest)
You'll need to be more specific. You can suck an entire file into one buffer, read byte by byte, read by lines... Do you have to handle text encodings?
you probably "do not" want to read byte by byte. in general, unless you are dealing with large files, just read the whole thing, then process it.
here's a general example:
fn readFile(allocator: Allocator, path: []const u8) ![]const u8 {
var file = try std.fs.cwd().openFile(path, .{});
defer file.close();
var fsz = (try file.stat()).size;
var br = std.io.bufferedReader(file.reader());
var reader = br.reader();
return try reader.readAllAlloc(allocator, fsz);
}
so take a file descriptor, get its size, make a reader and tell it to read by allocating on the heap?
or you can use std.fs.cwd().readFileAlloc (https://ziglang.org/documentation/master/std/#A;std:fs.Dir)
oh this one returns a slice?
It returns an Error Union Type because the operation can fail. But yes basically it returns a slice
right ![]u8
so i just do !void on main and use it with try
yes, you can also use catch if you want
👍
you'd probably still want to grab the size ahead of time here (although there are still cases this could cause FileTooBig anyway)
yeah you are right, while the function does use readToEndAllocOptions internally it just passes null so the default allocation in 1kb.
no sorry @wintry hollow the function already gets the file size to allocate before reading
if you want to suck it into a stack buffer instead you can do that too
no need for an allocator
Stack memory is more constrained than heap memory, so one must be cognizant of file sizes.
err, where? there's a 0 size which ultimately uses 1024 for a buffer size. the only other thing is a check to make sure the max size fits in to usize.
yes please
would probably be cleanest
oh wait i got an idea
i am going to use comptime to read it at compile time with an allocator
and store the value in a stack variable
you can use @embedFile for this https://ziglang.org/documentation/master/#embedFile
yeah solved then