Iterate over the lines in a file.
var line_buffer: [1024]u8 = undefined;
var it = try zul.fs.readLines("/tmp/data.txt", &line_buffer, .{});
defer it.deinit();
while (try it.next()) |line| {
std.debug.print("line: {s}\n", .{line});
}
path: []const u8
Absolute or relative path to the file.
buf: []const u8
Buffer to write the line into, the buffer length represents the maximum allowed line. If a line is longer than buf.len
next()
will return error.StreamTooLong
.
opts: zul.fs.LineIterator.Opts
Options that control the iterator.
delimiter: u8
- The delimiter to split on, defaults to '\n'
open_flags: std.fs.File.OpenFlags
- Flags to pass to the underlying std openFile
call.
On success, readLines
returns this a LineIterator
.
deinit(self: LineIterator)
Releases the resources associated with the iterator (i.e. it closes the file). This must be called the the iterator is no longer needed.
next(self: LineIterator) !?[]u8
Returns the next line, or null
if the the end of the file has been reached . The return value is only valid until the next call to next
or deinit
.
The return []u8
value may be a slice of the buf
parameter passed to readLines
or it may be a slice of the internal buffer
used for reading the file. In either case the lifetime is the same. When possible, a slice to the internal buffer is used to avoid a copy.
Due to issue 17985, readLines
should performance considerably better than the typical std solution involving a std.io.File
wrapped in a std.io.BufferedReader
exposed as an std.io.Reader
.
By default, readLines
will read from the file using a 4096 byte buffer. A different size can be specified via the readLinesSize
function:
var it = try zul.fs.readlinesSized(8192, "/tmp/data.txt", &line_buffer, .{});
The size must be comptime-known (i.e, a constant). The rest of the API is exactly the same.