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