Skip to content

Instantly share code, notes, and snippets.

@palash25
Last active July 27, 2023 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palash25/9806780ecbe280b89bd16256f5f46884 to your computer and use it in GitHub Desktop.
Save palash25/9806780ecbe280b89bd16256f5f46884 to your computer and use it in GitHub Desktop.
Zig code to read a file line by line
// Zig code to read and print a file line by line
const std = @import("std");
const fs = std.fs;
const io = std.io;
const debug = std.debug;
pub fn main() anyerror!void {
// use an absolute path
const path = "/home/testdata/testfile";
var f = try fs.openFileAbsolute(path, .{.mode = fs.File.OpenMode.read_only});
defer f.close();
var reader = f.reader();
var output: [100]u8 = undefined;
var output_fbs = io.fixedBufferStream(&output);
const writer = output_fbs.writer();
while(true) {
reader.streamUntilDelimiter(writer, '\n', null) catch |err| {
switch (err) {
error.EndOfStream => {
output_fbs.reset(); // clear buffer before exit
break;
}, // file read till the end
else => {
debug.print("Error while reading file: {any}\n", .{err});
return err;
},
}
};
var line = output_fbs.getWritten();
debug.print("Line: {s}\n", .{line});
// since steamUntilDelimiter keeps appending the read bytes to the buffer
// we should clear it on every iteration so that only individual lines are
// displayed on each iteration.
output_fbs.reset();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment