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"); const std = @import("std");
pub fn main() !void { 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| { 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 = std.fs.openFileAbsolute( const file = std.fs.cwd().openFile(
file_path, file_path,
.{ .mode = .read_only }, .{ .mode = .read_only },
) catch |err| { ) catch |err| {
@ -12,17 +20,25 @@ pub fn main() !void {
}; };
defer file.close(); defer file.close();
while (true) { print_from_stream(file.reader().any()) catch continue;
var ar = std.ArrayList(u8).init(std.heap.page_allocator); }
defer ar.deinit(); }
file.reader().streamUntilDelimiter( pub fn handle_stdin_input() void {
ar.writer(), print_from_stream(std.io.getStdIn().reader().any()) catch return;
'\n', }
null,
) catch break; pub fn print_from_stream(stream: std.io.AnyReader) !void {
while (true) {
std.debug.print("{s}\n", .{ar.items}); var line = std.ArrayList(u8).init(std.heap.page_allocator);
} defer line.deinit();
try stream.streamUntilDelimiter(
line.writer(),
'\n',
null,
);
std.debug.print("{s}\n", .{line.items});
} }
} }