Update Zig Cat example

* added reading from stdin if no paths are provided
* using streams to encapsulate common behaviour in print_from_stream
This commit is contained in:
Maciej Krzyżanowski 2024-09-04 23:53:11 +02:00
parent c36cac1b06
commit 09b4c503b9

View File

@ -1,9 +1,17 @@
const std = @import("std");
pub fn main() !void {
if (std.os.argv.len > 1) {
handle_file_input();
} else {
handle_stdin_input();
}
}
pub fn handle_file_input() void {
for (std.os.argv[1..]) |file_path_sent| {
const file_path = std.mem.span(file_path_sent);
const file = std.fs.openFileAbsolute(
const file = std.fs.cwd().openFile(
file_path,
.{ .mode = .read_only },
) catch |err| {
@ -12,17 +20,25 @@ pub fn main() !void {
};
defer file.close();
while (true) {
var ar = std.ArrayList(u8).init(std.heap.page_allocator);
defer ar.deinit();
print_from_stream(file.reader().any()) catch continue;
}
}
file.reader().streamUntilDelimiter(
ar.writer(),
pub fn handle_stdin_input() void {
print_from_stream(std.io.getStdIn().reader().any()) catch return;
}
pub fn print_from_stream(stream: std.io.AnyReader) !void {
while (true) {
var line = std.ArrayList(u8).init(std.heap.page_allocator);
defer line.deinit();
try stream.streamUntilDelimiter(
line.writer(),
'\n',
null,
) catch break;
);
std.debug.print("{s}\n", .{ar.items});
}
std.debug.print("{s}\n", .{line.items});
}
}