Show how to read a file line by line in Zig.
- User
Show how to read a file line by line in Zig.
- Assistant
Here is an example of how to read a file line by line in Zig:
const std = @import("std"); pub fn main() !void { var file = try std.fs.cwd().openFile("file.txt", .{}); var buffer: [1024]u8 = undefined; while (try file.readUntilDelimiterOrEof(&buffer, '\n')) |line| { std.debug.print("Line: {s}\n", .{line}); } try file.close(); }The key points:
- Open the file for reading with
std.fs.cwd().openFile() - Use
file.readUntilDelimiterOrEof()to read each line into a buffer, delimited by newline - It returns an optional which is iterated over with the
|line|syntax - Print out each line
- Close the file after reading
This allows iterating over the file line by line without having to manually handle buffering and newlines.
- Open the file for reading with
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.