#reading a file in zig

1 messages · Page 1 of 1 (latest)

old kettle
#

i wanna read a plain text file in zig

vale perch
#

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?

old kettle
#

i think i wanna suck it into a stack buffer?

#

i think i wanna read byte by byte

wintry hollow
#

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.

old kettle
#

ok

#

how do i read the whole thing

#

i guess i take a slice of the entire thing?

wintry hollow
#

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);

}

old kettle
#

so take a file descriptor, get its size, make a reader and tell it to read by allocating on the heap?

frank stone
regal sky
frank stone
old kettle
#

so i just do !void on main and use it with try

frank stone
#

yes, you can also use catch if you want

old kettle
#

oh catch nice

#

ok thanks alot everyone

frank stone
#

👍

wintry hollow
frank stone
#

no sorry @wintry hollow the function already gets the file size to allocate before reading

pearl quail
#

no need for an allocator

vale perch
#

Stack memory is more constrained than heap memory, so one must be cognizant of file sizes.

pearl quail
#

or say that large files are unsupported

#

depends on your application

wintry hollow
old kettle
#

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

old kettle
#

yeah solved then