Update Zig Cat Example

* Added file open error handling, by catching an error.
* Added better streamUntilDelimiter error handling. You can try,
  but you can't catch.
* Use ArrayList's writer to dynamically allocate space needed to
  read a line.
This commit is contained in:
Maciej Krzyżanowski 2024-09-04 00:01:58 +02:00
parent c26b902914
commit c36cac1b06

View File

@ -3,24 +3,26 @@ const std = @import("std");
pub fn main() !void {
for (std.os.argv[1..]) |file_path_sent| {
const file_path = std.mem.span(file_path_sent);
const file = try std.fs.openFileAbsolute(
const file = std.fs.openFileAbsolute(
file_path,
.{ .mode = .read_only },
);
) catch |err| {
std.debug.print("error occurred while opening file: {s}\n", .{@errorName(err)});
return;
};
defer file.close();
while (true) {
const rw_result = file.reader().streamUntilDelimiter(
std.io.getStdOut().writer(),
var ar = std.ArrayList(u8).init(std.heap.page_allocator);
defer ar.deinit();
file.reader().streamUntilDelimiter(
ar.writer(),
'\n',
null,
);
) catch break;
if (rw_result) |_| {} else |_| {
break;
}
std.debug.print("\n", .{});
std.debug.print("{s}\n", .{ar.items});
}
}
}